【问题标题】:Vue JS: vuex state not updating the component after change [duplicate]Vue JS:更改后vuex状态不更新组件[重复]
【发布时间】:2019-06-08 20:44:05
【问题描述】:

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

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

为了能够从其他组件更新 m&lt;InfoBar /&gt;,我决定尝试使用 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 突变来更新文本:

其他.vue:

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

我用 Vue 开发者工具检查了infoBarTextstate 并成功更改为"Text from Component" 但它没有更改组件中的文本。

我做错了什么?

【问题讨论】:

  • 相似但不一样...

标签: vue.js vuejs2


【解决方案1】:

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

【讨论】:

  • 使用计算仍然对我不起作用.... :(
  • 花了一整天的时间寻找这个答案!不敢相信'计算不会在答案中出现更多时间;-)
  • 我也遇到了同样的问题,我已经在computed中使用了,但是还是不能用,请问有人有ans吗?
  • @Tyguy7 你找到答案了吗? Computed 对我也不起作用。
猜你喜欢
  • 2019-07-30
  • 2020-02-10
  • 1970-01-01
  • 2019-08-06
  • 2019-09-25
  • 2022-07-16
  • 2020-08-04
  • 2018-06-14
  • 2019-03-20
相关资源
最近更新 更多