首页 > 解决方案 > 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.$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 实例的文本颜色设为红色?

谢谢

标签: vue.js

解决方案


您应该能够使用在两个实例之间共享的总线来完成此操作。您可以通过在原型链中创建一个新的 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:{}
})

推荐阅读