组件关系可分为父子组件通信、兄弟组件通信、跨级组件通信。
自定义事件:
当子组件需要向父组件传递数据时,就要用到自定义事件。v-on除了监听DOM事件外,还可以用于组件之间的自定义事件。
子组件用$emit() 来触发事件,父组件用$on()来监听子组件的事件。
父组件也可以直接在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件,示例:
![](https://img.haomeiwen.com/i15705400/1bc4c38088331756.png)
<div id="app">
<p>总数:{{total}}</p>
<my-component @increase="handleGetTotal" @reduce="handleGetTotal"></my-component>
</div>
<script>
Vue.component('my-component', {
// template的内容如果有换行,就要有'\'
// 点击按钮则触发方法
template: '\
<div>\
<button @click="handleIncrease">+1</button>\
<button @click="handleReduce">-1</button>\
</div>',
data: function() {
return{
counter: 0
}
},
methods: {
// 点增加按钮,则将定义返回的data:counter+1,传递参数,并且返回到父组件increase,并触发handleGetTotal方法
handleIncrease: function() {
this.counter ++;
this.$emit('increase', this.counter);
},
handleReduce: function() {
this.counter --;
this.$emit('reduce', this.counter);
}
}
});
// 挂载
var app = new Vue({
el: '#app',
data: {
total:0
},
methods: {
handleGetTotal: function(total) {
this.total = total;
}
}
})
</script>
子组件有两个按钮,分别实现加1和减1的效果,在改变组件的data“counter”后,通过$emit()再把它传递给父组件,父组件用v-on:increase和v-on:reduce。$emit()方法的第一个参数是自定义事件的名称,例如示例的increase和reduce后面的参数都是要传递的参数,可以不填或者填写多个。
使用v-model代替监听功能,实现双向绑定
![](https://img.haomeiwen.com/i15705400/aef85e0072dc4640.png)
<div id="app">
<p>总数:{{total}}</p>
<my-component v-model="total"></my-component>
<button @click="handleReduce">-1</button>
</div>
<script>
Vue.component('my-component', {
props: ['value'],
template: '<input :value=value @input="updateValue">',
methods: {
updateValue: function (event) {
this.$emit('input', event.target.value);
}
}
});
var app = new Vue({
el: '#app',
data: {
total: 0
},
methods: {
handleReduce: function(){
this.total --;
}
}
})
</script>
在自定义组件上使用v-model指令,绑定数据。若要实现这样一个具有双向绑定的v-model组件要满足下面两个要求:1.接收一个value属性;2.在有新的value时触发input事件。
vue组件的3个API来源:props传递数据,events触发事件,slot内容分发。
网友评论