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

发布时间:2020-09-18 23:16:07 作者:m0_37068028
来源:脚本之家 阅读:147

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的使用详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

推荐阅读:
  1. 如何在vue2.0中自定义组件
  2. Vue2.0中怎么实现数据的双向绑定

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue2.0 on emit

上一篇:Vue组件间的通信pubsub-js实现步骤解析

下一篇:详解webpack的proxyTable无效的解决方案

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》