Vue组件通信
在这里主要介绍一下三个方面的通信,其他的更高级的通信在后面介绍
- 父子组件通信
- 子父组件通信
- 非父子组件通信
- ref链实现
- bus事件总线【 自定义事件 】
父子组件通信
组件实例的作用域是孤立的。这意味着不能 (也不应该) 在子组件的模板内直接引用父组件的数据。父组件的数据需要通过 prop 才能下发到子组件中。
Vue.component('Father',{
template: '#father',
data () {
return {
money: 2000
}
}
})
Vue.component('Son',{
template: '#son',
props: ['money']//接受父组件传来的值
})
<template id="father">
<div>
father
<Son :money = "money"></Son>
//将父组件中的data money传给子组件的money
</div>
</template>
<template id="son">
<div>
son
<p> 老爸给了我 {{ money }} 生活费 </p>
</div>
</template>
经过这两步子组件就可以得到父组件的数据
子父组件通信
子父组件之间的通信是通过自定义事件进行通信的,接受子组件发过来的数据
父组件定义一个自定义事件,接受子组件发送过来的数据,就可以实现子父组件之间的通信
<template id="father">
<div>
<Son @aa = "get"></Son>
<!-- 这个的@后的事件名称可以任意 @后的就是自定义事件, =后的就是事件处理程序 -->
<p>小金库现在有:{{xiaojinku}}</p>
</div>
</template>
<template id="son">
<div>
<button @click = "give">发红包</button>
</div>
</template>
//
//原理是通过自定义时间发布时间来接受子组件传过去的参数
Vue.component('Father',{
template:"#father",
data(){
return {
xiaojinku:0
}
},
methods:{
get(val){
this.xiaojinku = val;
}
}
})
Vue.component('Son',{
template:"#son",
data(){
return {
hongbao:1000
}
},
methods:{
give(){
this.$emit('aa',this.hongbao)
}
}
})
非父子组件通信
ref链方式
这种方法适用于一个父组件中的子组件的通信,如一个父组件中有两个子组件
这种方法的原理是通过将其中一个子组件的数据传递给父组件,父组件再将数据传递给另一个子组件:子——>父——>另一个子
<template id="father">
<div>
<Sister :kick = "kick"></Sister>
<Borther ref = 'son'></Borther>
<!-- father组件中refs属性 -->
</div>
</template>
<template id="sister">
<div>
<button @click = "kick">打人</button>
</div>
</template>
<template id="borther">
<div>
<img v-if = "flag" src="./img/1.jpg" alt="">
</div>
</template>
父组件中使用ref属性,可以取到Son组件的函数change()
Vue.component('Father',{
template:"#father",
methods:{
kick(){
//通过父组件的$refs属性拿出数据
this.$refs.son.change()
}
}
})
Vue.component('Sister',{
template:"#sister",
props:['kick']
})
Vue.component('Borther',{
template:"#borther",
data(){
return {
flag:false
}
},
methods:{
change(){
this.flag=true;
}
}
})
bus事件总线实现通信
若两个组件相互之间的嵌套很深的时候,用ref解决会很繁琐,这时就用到了bus总线解决
bus总线解决通信问题的原理是,建立一个实例,将各个组件中的方法都写作bus上的自定义事件,因为是同一实例上的方法,就可以相互通信了
var bus = new Vue();
//bus事件总线思维: 将new Vue() 的实例作为全局变量,用来联通非父子组件
Vue.component('Tall',{
template:"#tall",
data(){
return {
val:''
}
},
methods:{
addtodo(){
bus.$emit('add',this.val)
}
}
})
Vue.component('Dell',{
template:"#dell",
data(){
return {
todos:[{
id:1,
task:'吃饭'
},{
id:2,
task:'睡觉'
},{
id:3,
task:'学习'
}]
}
},
mounted(){
var _this = this;
bus.$on('add',function(val){
_this.todos.push({
id:_this.todos.length+1,
task:val
})
})
}
})
<template id="tall">
<div>
<input type="text" v-model = "val" @keyup.enter = "addtodo">
</div>
</template>
<template id="dell">
<div>
<ul>
<li v-for = "todo in todos" :key = "todo.id">{{todo.task}}</li>
</ul>
</div>
</template>