开篇
先来一张图:
了解组件通信首先要了解自定义事件
,因为当子组件向父组件传递数据时,就要用到他,后面开始我们的正题
1.1分类
组件通信可以分为:父子组件通信、兄弟组件通信、跨级组件通信
当子组件向夫父组件传递数据时就要用到,v-on除了监听DOM事件外,还可以用于组件的自定义事件子组件使用$emit()
来触发事件,父组件用$on()
来监听父组件也可以直接在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件
使用 $on(eventName) 监听事件
使用 $emit(eventName) 触发事件
1.1.1初识组件props
可能有些小伙伴对props这个组件还“不够”了解或者清楚,现在我这里举一些关于props有关的例子,如果非常清楚了,可以跳过这一节😎😎关于props这一节我本来是想要单独出一个文章“拿下它”,后续再看看有没有时间吧,这里举的例子是官网的例子噢
<div id="blog-post-demo" class="demo">
<blog-post title="My journey with Vue"></blog-post>
<blog-post title="Blogging with Vue"></blog-post>
<blog-post title="Why Vue is so fun"></blog-post>
</div>
Vue.component('blog-post', {
props: ['title'],
template: '<h2>{{title}}</h2>'
});
var app = new Vue({
el: '#blog-post-demo'
})
props非常简单,那就是——给子组件传递数据用的!通过这个例子,我想你应该知道谁是“父”,谁是“子”了吧🙋♀️
1.2案例
🙋♀️🙋♀️那就来看一个例子
<div id="app">
<p>总数:{{total}}</p>
<my-component @increase="handleGetTotal" @reduce="handleGetTotal">
</my-component>
</div>
<script>
Vue.component('my-component', {
template: '\
<div>\
<button @click="handleIncrease">+1</button>\
<button @click="handleReduce">-1</button>\
</div>',
data: function(){
return {
counter: 0
}
},
methods: {
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.3使用v-model玩玩
v-model的最大的特点:双向绑定,注意,是双向,双方谁变了都会变,ok,那再来看一个例子
<div id="app">
<p>总数:{{total}}</p>
<my-component v-model="total"></my-component>
<button @click="handleGetTotal">点我试试!!</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: {
handleGetTotal: function(){
this.total--;
}
}
})
</script>
效果图截图
再来分析一波!!