Vue.js Vue JS:vuex状态在更改后未更新组件

Vue.js Vue JS:vuex状态在更改后未更新组件,vue.js,vuejs2,Vue.js,Vuejs2,我创建了一个信息栏,一个我想用组件信息更新的区域。我将其添加为App.vue的子项: <template> <div id="app"> <InfoBar /> // my info-bar <router-view/> </div> </template> infobar.vue <template> <div> {{infoString}

我创建了一个信息栏,一个我想用组件信息更新的区域。我将其添加为
App.vue
的子项:

<template>
  <div id="app">
    <InfoBar />  // my info-bar
    <router-view/>
  </div>
</template>
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      
    }
  }
我使用Vue开发工具检查了
infoBarText
状态,它成功地更改为
“来自组件的文本”
,但没有更改组件中的文本


我做错了什么?

您应该使用
计算的
而不是
数据
,因为
数据
本身在分配后不会反应。这将解决您的问题:

export default {
  name: "infoBar",
  computed: {
    infoString: function() {
      return this.$store.state.infoBarText;
    }
  }
}
概念证明:

const infobar=Vue.component('infobar'{
模板:“#信息栏模板”,
计算:{
infoString:function(){
返回store.state.infoBarText;
}
}
});
const store=新的Vuex.store({
声明:{
infoBarText:“来自Vuex存储区的文本”,//调试的初始文本
},
突变:{
setInfoBarText(状态,文本){
state.infoBarText=文本;
}
}
});
新Vue({
el:“#应用程序”,
方法:{
updateText(){
提交(“setInfoBarText”,“来自组件的文本”);
}
}
});

更新文本
{{infoString}}

类似但不相同…使用computed仍然不适用于我…:(花了一整天的时间寻找这个答案!不敢相信“计算机”不会在答案中出现更多的时间;-)
mounted() {
 this.$store.commit("setInfoBarText", "Text from Component");
}
export default {
  name: "infoBar",
  computed: {
    infoString: function() {
      return this.$store.state.infoBarText;
    }
  }
}