vue.js - Vue实例之间如何通信

标签 vue.js

如果我定义一个像这样的组件:

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/

相关文章:

javascript - vue-router 为什么当我刷新一个 URL 包含 id 的页面时,我会丢失页面的所有设计

javascript - 在 vuetify 中设置 select 的高度

javascript - Vue Chart.js - 图表在数据更改时不更新

vue.js - VueJS : Prop's property change is not detected inside sub-components

html - 将插槽传递到 Vue.js 中的插槽

vue.js - 如何将 ASP Core Web API VueJS 站点部署到 IIS

vue.js - Vue Boolean prop 是否可以在存在时为真,在不存在时为假?

javascript - v-model 并选择多个

vue.js - Vue - 检查你是否在 v-for 循环的最后一个 Prop 上

javascript - 移动设备上的 MS Teams 选项卡中的身份验证