Vue JS:Vuex状态在更改后未更新组件

时间:2019-01-14 20:25:46

标签: vue.js vuejs2

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

<template>
  <div id="app">
    <InfoBar />  // my info-bar
    <router-view/>
  </div>
</template>

为了能够从其他组件更新m <InfoBar />,我决定尝试使用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;
            }
        }

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      
    }
  }

现在,我想使用其他组件的Vuex突变来更新文本:

other.vue:

mounted() {
 this.$store.commit("setInfoBarText", "Text from Component");
}

我使用Vue开发人员工具检查了state中的infoBarText,并将其成功更改为"Text from Component",但未更改组件中的文本。

我做错了什么?

1 个答案:

答案 0 :(得分:6)

您应该使用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>

相关问题