父子组件通信-$emit

父子组件使用$emit和v-on时,子组件使用$emit触发,父组件在实例中v-on自定义事件监听。

注意:父组件监听子组件触发的事件,不能用$on侦听子组件抛出的事件,而必须在模板里直接用v-on绑定。

下面是官方文档给出的例子:

HTML:

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment1="incrementTotal"></button-counter>
  <button-counter v-on:increment1="incrementTotal"></button-counter>
</div>
JS:
Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1 //组件模板中的counter
      this.$emit('increment1')//触发自定义事件,这里的参数是自定义事件名称
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1  //父实例下的total
    }
  }
})






猜你喜欢

转载自blog.csdn.net/zx_p24/article/details/74294691