在Vuejs中的不同组件之间共享数据 [英] Share data across different components in Vuejs
问题描述
在下面给出迷你Vuejs应用.
Given the mini Vuejs app down below.
当我单击自己的增减按钮之一时,计数器"组件中的值将更新,但字母"内部的值不会更新.
关于如何在这两个组件之间共享相同数据以便它们自动更新的任何想法?
When I click one of my increment/decrement buttons, the value within the "counter" component updates but the value inside "alphabet" doesn't.
Any ideas on how can I share the same data across those two components so that they automatically update ?
var counter = Vue.extend({
props: ['start'],
template: '#counter',
data: function() {
return {
value: this.start
}
},
methods: {
increment: function() {
this.value++
},
decrement: function() {
this.value--
}
}
});
var alphabet = Vue.extend({
props: ['value'],
template: '#alphabet',
data: function() {
return {
value: 0
}
}
});
new Vue({
el: '#app',
data: {
val: 5
},
components: {
counter: counter,
alphabet: alphabet
}
});
<script id="counter" type="text/template">
<button @click="increment">+</button> {{ value }}
<button @click="decrement">-</button>
</script>
<script id="alphabet" type="text/template"> {{ value }} </script>
<div id="app">
<counter :start="val"></counter>
<alphabet :value="val"></alphabet>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.17/vue.js"></script>
推荐答案
设置方式存在2个问题.它在这里工作: https://jsfiddle.net/j9hua7c8/
There were 2 issues with the way you set it up. Here it is working: https://jsfiddle.net/j9hua7c8/
第一个问题是在counter
组件中,您创建了一个名为value
的新变量,其值为this.start
.这采用了start
的值并将其分配给value
,但是由于value
是一个新变量,因此不再与start
同步.更新版本:
First issue was in the counter
component, you created a new variable called value
and it a value of this.start
. This took the value of start
and assigned it to value
, but since value
was a new variable it was no longer sync'd to start
. Updated version:
var counter = Vue.extend({
props: ['value'],
template: '#counter',
methods: {
increment: function() {this.value++},
decrement: function() {this.value--}
}
});
第二件事是,为了使子变量双向同步,您需要在绑定上使用.sync
修饰符.默认情况下,它们只是单向绑定.更新:
Second thing is, in order to have a child variable sync two-ways, you need to use the .sync
modifier on the binding. By default, they are only one-way bindings. Updated:
<counter :value.sync="val"></counter>
您还可以使用 $ dispatch 和
You can also use $dispatch and $broadcast to communicate between parent and child components if that is better for your use case.
这篇关于在Vuejs中的不同组件之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!