当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue2.0 中#$emit,$on的使用详解

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

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的使用详解,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网