首页 > 解决方案 > VueJS - Vuex 状态更新时组件不更新

问题描述

我有一个 vuex 商店,里面有一个名为“columnChoice”的项目。我有一个在文本框中更新它的组件,以及一个更新它并验证它是正整数的计算属性。但是,组件的计算属性没有更新(根据开发工具),即使 vuex 存储肯定是更新(也根据开发工具)。

这是代码,我删除了其他不相关的方法/值,但如果似乎缺少某些东西,请告诉我。

我已经尝试将计算设置从“...mapState([])”一个更改为这个,我还尝试了具有单独 set 和 get 函数的 v-model 设置。

Vuex 商店index.js

import Vuex from 'vuex'

export default new Vuex.Store({
  state: {
    columnChoice: 1,
    processingStatus: 0,
    columnError: 0
  },
  mutations : {
    resetVars(state) {
      state.processingStatus = 0
      state.columnError = 0
      state.columnChoice = 1
    },

    setProcessingStatus(state, v) {
      state.processingStatus = v
    },

    columnError(state) {
      state.columnError = 1
    },
    columnGood(state) {
      state.columnError = 0
    },
    columnSet(state, v) {
      state.columnChoice = v
    }
  }
})

组件:

<template>
  <div class="row p-2">
    <div class="col-2">Column in reference file</div>
    <div class="col-10"><input type=text size=3 :value="columnChoice" @change="verifyColumn" id="columnChoice"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'ColumnChoice',
  computed: {
    ...mapState([
      'columnChoice'
    ]),
  },
  methods: {
    verifyColumn(e) {
      if (isNaN(e.target.value) || e.target.value < 1) {
        this.$store.commit('columnError')
        this.$store.commit('columnSet', e.target.value)
      } else {
        this.$store.commit('columnGood')
        this.$store.commit('columnSet', e.target.value)
      }
    },
  }
}
</script>

此外,在将文本字段中的值更改为 5 并在开发工具中选择此组件(将其分配给 $vm0)后,我得到以下信息,表明状态确实已更新并可通过组件访问,但计算出的属性只是没有更新:

$vm0.$store.state.columnChoice
> "5"
$vm0._computedWatchers.columnChoice.value
> "1"

标签: javascriptvue.jsvuex

解决方案


好吧,我想通了。结果在我的 index.html 文件中,除了使用从 NPM 导入的实例之外,我还一直从 CDN 获取 vue 实例


推荐阅读