如果我定义一个组件,例如:
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实例的文本变为红色?
谢谢
答案 0 :(得分:2)
您应该能够使用两个实例之间共享的总线来完成此任务。您可以通过在原型链中创建新的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:{}
})