首页 > 解决方案 > 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 开发人员工具检查了stateinfoBarText,它成功更改为,"Text from Component"但它没有更改组件中的文本。

我做错了什么?

标签: vue.jsvuejs2

解决方案


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


推荐阅读