Vue.js中如果父组件想访问子组件的data或method则可以在子组件声明ref
属性,父组件通过$refs
来访问,那么子组件如果想访问父组件的事件我们该如何处理呢?
Vue.js中父组件通过prop
传递数据给子组件,而想要将子组件的数据传递给父组件,则可以通过自定义事件的绑定。参考
1、每个Vue实例都实现了事件接口,即:
- 使用
$on(eventName)
监听事件 - 使用
$emit(eventName)
触发事件
父组件可以在使用子组件的地方直接用v-on来监听子组件触发的事件。
2、父组件HTML内引用子组件<button-counter>
<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实例:
Vue.component('button-counter',{
template: '<button v-on:click="increment">{
{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit('increment')
}
},
})
父组件Vue实例:
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
在子组件里面把点击事件(click)绑定给了函数increment,点击子组件按钮将会触发位于子组件的increment函数,函数内再通过this.$emit('increment')
触发当前实例上的事件(附加参数都会传给监听器回调)。
子组件在调用了increment函数的时候,通过$emit
来通知父组件。这样就形成父子组件间的相互呼应传递信息。
在平常的组件通讯,父组件是通props
参数对子组件进行传递,而子组件向父组件传递则可以使用自定义事件
了。
这样,父组件和子组件已经解耦,子组件收到的是父组件内部的实现。