我创建了一个信息栏,我想用组件中的信息更新一个区域.我把它作为孩子添加App.vue:
<template>
<div id="app">
<InfoBar /> // my info-bar
<router-view/>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
为了能够<InfoBar />从其他组件更新m ,我决定尝试使用Vuex并使用mutations更改信息:
Vuex商店:
export const store = new Vuex.Store({
state:{
infoBarText: "Text from Vuex store" , // initial text for debugging
},
mutations:{
setInfoBarText(state,text){
state.infoBarText = text;
}
}
Run Code Online (Sandbox Code Playgroud)
infobar.vue
<template>
<div>
{{infoString}} // the result is always "Text from Vuex store"
</div>
</template>
<script>
export default {
name: "infoBar",
data() {
return {
infoString: this.$store.state.infoBarText
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想使用其他组件的Vuex变异更新文本:
other.vue:
mounted() {
this.$store.commit("setInfoBarText", "Text from Component");
}
Run Code Online (Sandbox Code Playgroud)
我检查了state的infoBarText与Vue公司的开发工具和它成功地改变"Text from Component",但它没有改变在组件中的文本.
我做错了什么?
Ter*_*rry 11
您应该使用computed而不是data,因为data一旦分配它本身就不会被动.这将解决您的问题:
export default {
name: "infoBar",
computed: {
infoString: function() {
return this.$store.state.infoBarText;
}
}
}
Run Code Online (Sandbox Code Playgroud)
证明的概念:
const infobar = Vue.component('infobar', {
template: '#infobar-template',
computed: {
infoString: function() {
return store.state.infoBarText;
}
}
});
const store = new Vuex.Store({
state: {
infoBarText: "Text from Vuex store", // initial text for debugging
},
mutations: {
setInfoBarText(state, text) {
state.infoBarText = text;
}
}
});
new Vue({
el: '#app',
methods: {
updateText() {
store.commit("setInfoBarText", "Text from Component");
}
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.22/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>
<div id="app">
<InfoBar></InfoBar>
<button @click="updateText">Update text</button>
</div>
<script type="text/x-template" id="infobar-template">
<div>
{{infoString}}
</div>
</script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4958 次 |
| 最近记录: |