如果我定义一个像这样的组件:
Vue.component("hello", {
name: "hello",
data: ()=>{ return {color:"black"} },
template: "<div><div :style='{color:color}'>TEST</div><button @click='turnred'>TURN RED</button></div>",
methods:{
turnred(){ this.$emit("turnred","red") }
},
created(){
this.$on("turnred", function(c){this.color = c;})
}
})
如果我创建 2 个实例:
<div id="a1">
<hello />
</div>
<div id="a2">
<hello />
</div>
new Vue({
el: "#a1",
data:{}
})
new Vue({
el: "#a2",
data:{}
})
我想知道如何让两个 hello 实例的文本颜色都变成红色?
谢谢
最佳答案
您应该能够使用在两个实例之间共享的总线来完成此操作。您可以通过在原型(prototype)链中创建一个新的 Vue 实例来创建总线。
Vue.prototype.$bus = new Vue();
Vue.component("hello", {
name: "hello",
data: ()=>{ return {color:"black"} },
template: "<div><div :style='{color:color}'>TEST</div><button @click='turnred'>TURN RED</button></div>",
methods:{
turnred(){ this.$bus.$emit("turnred","red") },
changeColor(color) {
this.color = color;
}
},
created(){
this.$bus.$on("turnred", this.changeColor)
},
beforeDestroy() {
this.$bus.$off("turnred", this.changeColor);
}
})
new Vue({
el: "#a1",
data:{}
})
new Vue({
el: "#a2",
data:{}
})
关于vue.js - Vue实例之间如何通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54260346/