1.总线模式
非父子之间传值,可以采用发布订阅模式,这种模式在 Vue 中被称为总线机制,或者叫做
Bus
/ 发布订阅模式 / 观察者模式
<div id="app">
<!-- 非父子组件间的传值 -->
<child content="DELL"></child>
<child content="Lee"></child>
</div>
<script>
Vue.prototype.bus=new Vue();
//目的:给Vue的prototype上挂载了一个bus属性,指向了Vue的实例
//只要我们后面new Vue或者创建组件的时候,每一个组件上都会有bus这个属性
//原因就是我们将Vue的实例挂载在Vue类的prototype(原型对象)上面,
//那么后面有Vue类创建的任何实例都会继承bus属性(同一个Vue实例)
Vue.component('child',{
props:{
content:String
},
data:function(){
return {
selfContent:this.content
}
},
template:'<div @click="handleClick">{{selfContent}}</div>',
methods:{
handleClick:function(){
this.bus.$emit('change',this.selfContent);
//this.bus
//[1]表明了当前组件继承了Vue类的prototype的属性bus
//[2]this.bus指向的一个Vue的实例,故而可以使用$emit()方法
}
},
mounted:function(){//生命周期钩子
var _this=this;
//当前子组件监听bus的改变
//this.bus是Vue的实例,故而可以调用$on()监听事件
//this.bus.$on可以监听bus上触发的事件
this.bus.$on('change',function(msg){
//alert(msg);
//调试此处会弹出2次同样的值
//因为触发其中的一个组件,两个组件都会监听同一个change事件,从而弹出2次
_this.selfContent=msg;
})
}
})
var vm=new Vue({
el:"#app",
})
</script>