vue.js - 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 实例来创建总线。
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:{}
})
推荐阅读
- react-native - 使用 Linking API 打开天气默认应用程序?
- r - 如何检查我的数据框中的日期范围是否与另一个数据框中的任何(特定于 ID)范围重叠
- javascript - 根据点击量逐渐模糊图片(React-Native)
- python-3.x - Discord bot 检查消息作者是否具有管理权限
- sas - PROC genmod 的正确重复语句
- javascript - JS值可以是数组和函数吗?Array.isArray(v) + typeof v === '函数'
- php - 多个 foreach 循环语句
- css - 圆圈中的图像不完全可见
- javascript - 有没有一种有效的方法来遍历 avro 模式?
- python - Mac 上 PyCharm 中的语音识别缺少 PyAudio