如何从根 Vue.js 广播到所有组件 [英] How to broadcast to all components from root Vue.js
问题描述
我想向 vue.js 2
中的所有子组件$emit
一些数据,这是我的代码:
根组件
const app = new Vue({创建:函数(){//这是一些承诺,完成后下面的行运行this.$emit('foo', 'bar');}});
子组件
<脚本>导出默认{创建:函数(){this.$on('foo', function(data) {控制台日志(数据);});}}<脚本>
它不起作用.
有没有办法从root向所有子组件广播一些数据?
Vuejs 是自下而上的方法,意味着首先编译子组件并请求 this.$on
所以广播在这里不起作用$emit
-$on
在子组件中使用 props
来观察根数据的变化,给出这个例子,其中 child1
和 child2
具有相同的名为 名称代码>
var child1 = Vue.extend({模板:<div>子组件1:Niklesh:{{name}}<div v-if='loading'>正在加载...</div></div>",道具:['name','loading']});var child2 = Vue.extend({模板:<div>子组件1:Rishi:{{name}}<div v-if='loading'>正在加载...</div></div>",道具:['name','loading']});var app = new Vue({el: "#vue-instance",数据: {姓名: "...",加载:真实},安装(){var vm = 这个;设置超时(函数(){vm.name = "Raut";vm.loading = false;}, 1000);},成分: {孩子1,孩子2},})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script><div id="vue-instance"><child1 :name="name" :loading="loading"></child1><child2 :name="name" :loading="loading"></child2>
I want to $emit
some data to all child components in vue.js 2
and this is my code :
Root Component
const app = new Vue({
created: function(){
// here is some promise and after it done the below line runs
this.$emit('foo', 'bar');
}
});
Child Component
<template></template>
<script>
export default {
created: function() {
this.$on('foo', function(data) {
console.log(data);
});
}
}
<script>
It's not working.
Is there any way to broadcast some data to all child components from root?
Vuejs is bottom up approach, means child component is compiled first and ask for this.$on
so broadcasting will not work here with $emit
-$on
Use props
in child component to watch root data changes, giving this example where child1
and child2
having same root component data named name
var child1 = Vue.extend({
template: "<div>Child Component1 : Niklesh : {{name}} <div v-if='loading'>Loading...</div></div>",
props: ['name','loading']
});
var child2 = Vue.extend({
template: "<div>Child Component1 : Rishi : {{name}} <div v-if='loading'>Loading...</div></div>",
props: ['name','loading']
});
var app = new Vue({
el: "#vue-instance",
data: {
name: "...",
loading: true
},
mounted() {
var vm = this;
setTimeout(function() {
vm.name = "Raut";
vm.loading = false;
}, 1000);
},
components: {
child1,
child2
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>
<div id="vue-instance">
<child1 :name="name" :loading="loading"></child1>
<child2 :name="name" :loading="loading"></child2>
</div>
这篇关于如何从根 Vue.js 广播到所有组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!