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

发布时间:2019-05-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了关于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官网上面有个在线模板编译

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

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

脚本宝典总结

以上是脚本宝典为你收集整理的关于vue自定义事件中,传递参数的一点理解全部内容,希望文章能够帮你解决关于vue自定义事件中,传递参数的一点理解所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue