使用vuex或者bus总线机制可实现非父子组件的传值。
比如要实现点击上面的hello,下面的组件也变成hello,点击下面的world,上面的组件也变成world
<div id="app">
<child num='hello' ></child>
<child num='world' ></child>
</div>
<script>
Vue.prototype.bus=new Vue() //在vue的原型上挂载一个bus属性,并指向vue实例。只要之后去调用new Vue()或者创建组件的时候,都会有bus属性。为什么呢?因为每一个组件,每一个vue实例都是通过Vue这个类创建的,而我在Vue这个类上挂了bus属性,而且挂在prototype上。
Vue.component('child',{
props:["num"],
template:'<p @click="handleClick">{{num}}</p>',
methods:{
handleClick(){
//怎么传给另一个组件
this.bus.$emit("changeIt",this.num) //this.bus指的是实例上挂载的bus,而这个bus指向vue实例,所以它上面有$emit方法,这样就可以向外触发事件,当这个组件开始向外触发时,其他组件要监听,怎么监听,看下面的mounted生命周期钩子
},
mounted(){
this.bus.$on("changeIt",msg=>{
this.num=msg
})
}
})
var vm=new Vue({
el:'#app',
methods:{
handleChange(val){
console.log(val)
}
}
})
</script>
这么写代码,可以运行,但是控制台会报错。
报错的原因是在监听this.bus.$on时,改变了num的值,因为Vue中单向数据流的概念,父组件给子组件传值,子组件只能用不能直接修改从父组件传递过来的值。解决方法可以使用data,将父组件的值赋值给这个data中定义的变量,然后对这个变量进行操作。
<div id="app">
<child num='hello' ></child>
<child num='world' ></child>
</div>
<script>
Vue.prototype.bus=new Vue()
Vue.component('child',{
data(){
return{
con:this.num
}
},
props:["num"],
template:'<p @click="handleClick">{{con}}</p>',
methods:{
handleClick(){
this.bus.$emit("changeIt",this.con)
}
},
mounted(){
var that=this
this.bus.$on("changeIt",msg=>{
that.con=msg
})
}
})
var vm=new Vue({
el:'#app',
methods:{
handleChange(val){
console.log(val)
}
}
})
</script>