【问题标题】:Vuex TypeScript does not update String, but ArrayVuex TypeScript 不会更新 String,而是更新 Array
【发布时间】:2019-11-28 05:38:53
【问题描述】:

我目前正在使用 vue。商店正在更新我的数组,但不会更新我的字符串或布尔值。

我的代码是here:

我每秒提交一次字符串,但字符串没有显示在前端(vuex 开发工具显示状态正确,我的控制台日志没有)

我的商店如下所示:

const state: State = {
  cars: [],
  date: "false",
  carsCounter: 0,
};

我的出口:

const getters = {
  getCars(state: State) {
    return state.cars;
  },
  getDate(state: State) {
    return state.date;
  },
  getCarsCounter(state: State) {
    return state.carsCounter;
  }
};

const { read, commit, dispatch } = getStoreAccessors<State, State>("");

export const readCarsFromSse = read(getters.getCars);
export const readDate = read(getters.getDate);
export const readCarsCounter = read(getters.getCarsCounter);

我在日期组件中使用它,如下所示:

export default class DateVue extends Vue {
  date = readDate(store);
  cars = readCarsFromSse(store);
  testString = readCarsCounter(store);

  mounted() {
    Timeloader.loadTime();
  }

}

有谁知道为什么字符串没有更新,而数组却更新了?

谢谢

【问题讨论】:

  • read 函数是什么?
  • 对不起:const { read, commit, dispatch } = getStoreAccessors&lt;State, State&gt;("");

标签: javascript typescript vue.js vuex


【解决方案1】:

有谁知道为什么字符串没有更新,而数组却更新了?

在视图中,您使用一次做作从您的 Vuex 状态中获取值。当你得到一个数组时,Vuex 返回数组的观察者,并且项目值会保持最新。但原始值只是原始值。

这是一个解决方案,使用vuex-class

安装vuex-class:

npm install vuex-class

然后:

import { Component, Vue } from "vue-property-decorator";
import { Getter } from "vuex-class";

@Component
export default class DateVue extends Vue {
  @Getter("getDate")
  date!: string;
  @Getter("getCars")
  cars!: any[];
  @Getter("getCarsCounter")
  testString!: number;

  mounted() {
    Timeloader.loadTime();
  }
}

…或者没有vuex-class(auryn31提供的解决方案):

export default class DateVue extends Vue {
  get date() { return readDate(store); }
  // etc.
}

【讨论】:

  • 但我必须可以在 vuex 中使用原始值,他们也在文档中使用它?
  • @auryn31 哪个文档?
  • @auryn31 在本文档中,您将找到几个有关如何使用 Vuex 存储中的值的示例。你可以这样做:computed: { count () { return this.$store.state.count } } 或使用mapState Helper。
  • 谢谢,我通过使用对象而不是原始值来解决问题
  • 好的,答案是使用 get :-D get date() { return readDate(store); }
猜你喜欢
  • 2017-12-24
  • 1970-01-01
  • 2020-09-10
  • 2020-10-27
  • 2020-11-23
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多