vue2.0 中#$emit,$on的使用详解

2019/6/27 20:55:31

本文主要是介绍vue2.0 中#$emit,$on的使用详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

vue1.0中 vm.$dispatch 和 vm.$broadcast 被弃用,改用$emit,$on

vm.$on( event, callback )

监听当前实例上的自定义事件。事件可以由vm.$emit触发。回调函数会接收所有传入事件触发函数的额外参数。

vm.$emit( event, […args] )

触发当前实例上的事件。附加参数都会传给监听器回调。

例子:

//父组件
<template>
  <ratingselect @select-type="onSelectType"></ratingselect>
</template>
<script>
  data () {
   return {
    selectType: 0,
  },
  methods: {
   onSelectType (type) {
    this.selectType = type
   }
  }
</script>

父组件使用@select-type="onSelectType"@就是v-on的简写,监听由子组件vm.$emit触发的事件,通过onSelectType()接受从子组件传递过来的数据,通知父组件数据改变了。

// 子组件
<template>
 <div>
  <span @click="select(0, $event)" :class="{'active': selectType===0}"></span>
  <span @click="select(1, $event)" :class="{'active': selectType===1}"></span>
  <span @click="select(2, $event)" :class="{'active': selectType===2}"></span>
 </div>
</template>
<script>
  data () {
   return {
    selectType: 0,
  },
  methods: {
    select (type, event) {
      this.selectType = type
      this.$emit('select-type', type)
   }
  }
</script>

子组件通过$emit来触发事件,将参数传递出去。

以上所述是小编给大家介绍的vue2.0 中#$emit,$on的使用详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!



这篇关于vue2.0 中#$emit,$on的使用详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程