Vue:子组件如何跟父组件通信

我们知道,父组件使用 prop 传递数据给子组件。但子组件怎么跟父组件通信呢?这个时候 Vue 的自定义事件系统就派得上用场了。

使用 v-on 绑定自定义事件

每个 Vue 实例都实现了事件接口,即:

  • 使用 $on(eventName) 监听事件
  • 使用 $emit(eventName, optionalPayload) 触发事件

Vue 的事件系统与浏览器的 EventTarget API 有所不同。尽管它们运行起来类似,但是 $on 和 $emit 并不是addEventListener 和 dispatchEvent 的别名。

另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。

不能用 $on 监听子组件释放的事件,而必须在模板里直接用 v-on 绑定,参见下面的例子。

下面是一个例子:

<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>
Vue.component('button-counter', {
template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementCounter: function () {
this.counter += 1
this.$emit('increment')
}
},
})

new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})

0

 
 
 
 
再来举一个例子
<div id="example">
  <greet @said = "say"></greet>
</div>

Vue.component("greet", {
   template: "<button @click='i_said'>点击我</button>",
   methods:{
      i_said(){
         this.$emit("said", "Hello Vue!!")
      }
   }
})
new Vue({
  el:"#example",
  methods:{
    say(message){
       alert(message)
    }
  }
})

打开浏览器就会弹出来“Hello world”

子组件给父组件通信时可以添加参数,可以把子组件的属性传给父组件

 

 

posted @ 2018-04-15 17:13  珊迪·奇克斯  阅读(300)  评论(0编辑  收藏  举报