美文网首页
Vue 中的$emit $on 组件中的事件运用 非父子组件通信

Vue 中的$emit $on 组件中的事件运用 非父子组件通信

作者: sponing | 来源:发表于2016-12-20 10:33 被阅读0次

$emit

用v-on绑定 用本体用$emit绑定子组件:increment中的办法

html


<template>
  <div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  </div>
</template>
<script>
  export default{
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
}
</script>

子组件 $emit


<template>
  <div>
      <button v-on:click="increment">{{ counter }}</button>
  </div>
</template>
<script>
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
</script>

非父子组件通信

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的 Vue 实例作为中央事件总线:

var bus = new Vue()

// 触发组件 A 中的事件
bus.$emit('id-selected', 1)

// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
// ...
})

http://cn.vuejs.org/v2/guide/components.html#非父子组件通信

相关文章

网友评论

      本文标题:Vue 中的$emit $on 组件中的事件运用 非父子组件通信

      本文链接:https://www.haomeiwen.com/subject/chpxvttx.html