vue.js - Vue JS:更改后vuex状态不更新组件
问题描述
我创建了一个信息栏,这是一个我想用来自组件的信息更新的区域。我将它添加为以下内容的孩子App.vue
:
<template>
<div id="app">
<InfoBar /> // my info-bar
<router-view/>
</div>
</template>
为了能够<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;
}
}
信息栏.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
}
}
现在,我想使用来自其他组件的 Vuex 突变来更新文本:
其他.vue:
mounted() {
this.$store.commit("setInfoBarText", "Text from Component");
}
我使用 Vue 开发人员工具检查了state
它infoBarText
,它成功更改为,"Text from Component"
但它没有更改组件中的文本。
我做错了什么?
解决方案
您应该使用computed
而不是data
,因为data
一旦分配它本身就不是反应性的。这将解决您的问题:
export default {
name: "infoBar",
computed: {
infoString: function() {
return this.$store.state.infoBarText;
}
}
}
概念验证:
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");
}
}
});
<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>
推荐阅读
- python - 返回数组中长度最大的一系列递增顺序(Python)
- php - 在 PHP 中链接检查的优雅方式
- r - Rgdal readOGR 错误所有功能 NULL MacOS
- java - 将服务器时间更改为 EST
- javascript - 如何在 Angular 7 的模式中显示单个表格列的详细信息?
- elasticsearch - 在新添加的数据节点之间分配 Elasticsearch 的主分片
- python - Kivy ProgressBar 弹出窗口未正确显示
- c# - 从 ASP.NET Core 中创建的 cookie 获取信息
- llvm - 如何知道是否可以在 LLVM 中间接调用函数?
- pdf - 渲染文档时 Autodesk PDF Forge 查看器错误