Vue3自定义事件中,子组件有返回参数,父组件也有参数的处理方法

前言

在 vue 自定义事件中,子组件会通过 emit 向父组件传递参数,父组件执行回调函数。但是有时候父组件再执行回调时也会传入参数,如果直接给父组件回调函数传入参数会覆盖掉子组件的参数。我们有三种解决办法

正文

结合案例具体介绍一下

方法一: $event 方法

// 子组件中 Child.vue
<script setup>
  const { proxy } = getCurrentInstance()
  function edit (item) {
      console.log('子组件参数', childParam)
      proxy.$emit('edit', childParam)
  }
</script>

......

// 父组件接收参数
<Child @edit="editFun($event, parentParam)"></Child>

当子组件有参数返回时,在父组件中使用 $event 作为占位符,这里 $event 就代表了子组件返回的参数。这里 $event 位置没有限制,可以在第一位,也可以在最后一位

局限性: 只适合子组件返回一个参数的情况,如果子组件有多个参数返回,只能接收到第一个参数

方法二:箭头函数法

// 子组件中 Child.vue
<script setup>
  const { proxy } = getCurrentInstance()
  function edit (item) {
      proxy.$emit('edit', childParam1, childParam2)
  }
</script>

......

// 父组件接收参数
<Child @edit="(param1,param2)=>editFun(param1,param2,parentParam)""></Child>

<script setup>
function editFun(p1,p2,p3){
  ...
}
</script>

这种方法利用了一个箭头函数先把子模块返回的参数接收,然后再传递到回调函数中

使用是注意先接收子模块返回的参数,此方法对参数个数没有限制。

方法三:arguments 方法 (vue3中测试结果是不生效)

尤大大说的可以https://github.com/vuejs/vue/issues/5735, 但是我没测试成功
此方法类似于方法一,只不过是用 arguments 作为占位符,这里 argument 是一个数组

// 父组件接收参数
<Child @edit="editFun(arguments, scope.row)"></Child>

<script setup>
function editFun(p1,p2){
  ...
}
</script>
博客中所涉及到的图片都有版权,请谨慎使用
原文地址:https://www.cnblogs.com/shuiche/p/15652710.html