关于vue自定义事件中,传递参数的一点理解

例若有以下场景vue

<!-- 父组件 -->
<template>
  <div>
    <!--咱们想在这个dealName的方法中传递额外参数name -->
    <test-son v-for="item in list" @dealName="todo(item.name, arguments)" :item="item"></test-son>
  </div>
</template>

<script>
  export default {
    name: 'test-p',
    data() {
      return {
        list: [{
          name: '小王'
        }, {
          name: '小刚'
        }]
      }
    },
    methods: {
      todo(name, data) {
        console.log(name);
        console.log(data)
      }
    }
  }
</script>
<!-- 子组件 -->
<template>
  <div>
    <button @click="sendData">发射{{item.name}}</button>
  </div>
</template>

<script>
  export default {
    name: 'test-s',
    props: ['item'],
    methods: {
      sendData() {
        this.$emit('dealName', '王老吉');
      }
    }
  }
</script>

当咱们点击子组件button的时候就会打印对应的  xxx, 王老吉

接下来分析一下上述代码运做原理。
在vue官网上面有个在线模板编译app

clipboard.png

当咱们给模板上的自定义事件添加额外参数的时候,咱们的绑定函数就会被包裹上一层代码,function($event){xxx}
上述函数在子组件中emit的时候被调用,能够理解为 var dealName = function($event){xxx}
dealName.apply(vm, args);这其中因为事件函数在初始化的时候就进行了bind,因此在函数中this指向的是父组件的实例,而args则是$emit中传递的参数,因此在父组件中模板中经过argumens能够获取全部子组件emit的参数函数

相关文章
相关标签/搜索