<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
}
}
})
?这上面的是vue官方文档给出的父子通信组件的例子,是通过自定义事件实现的。
?我通过props 传function方式实现相同的功能下面是代码部分
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter :increment="incrementTotal"></button-counter>
<button-counter :increment="incrementTotal"></button-counter>
</div>
Vue.component('button-counter', {
template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
props:{
increment:{
type:Function
required:true
}
}
data: function () {
return {
counter: 0
}
},
methods: {
incrementCounter: function () {
this.counter += 1
//this.$emit('increment')
this.increment();
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
利用props特性一样可以实现vue父子组件的通信,在这里我想问问props实现和自定义事件实现都能实现那么在项目开发的时候该选择哪种方式呢,它们各有什么特点呢?我自己知道的就是通过自定义事件实现的配合vue-devtool工具方便调试,还有其他的吗?
文档原话