父组件是使用props传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件!
{{total}}
Vue.component('btn',{
template:'{{counter}}',
data:function () {
return{
counter:0
}
},
methods:{
increment:function () {
this.counter+=1
this.$emit('increment')
}
},
})
new Vue({
el:"#counter-event-example",
data:{
total:0
},
methods:{
incrementTotal:function () {
this.total+=1
}
}
})
运行结果如下:
点击下面的2个按钮中任意按钮,该按钮上的数字会累加,同时最上面的数字也会累加。
如果你想在某个组件的根元素上监听一个原生事件。可以使用.native修饰v-on。例如: