【问题标题】:Copy array from state using Array.from() from getter's return is not working on Vuex使用 getter 返回的 Array.from() 从状态复制数组在 Vuex 上不起作用
【发布时间】:2020-01-01 18:56:36
【问题描述】:

我的 State 上有一个数组,我用 Getter 得到了它。问题是我无法复制这些数组。我正在尝试:

export default {
data() {
 ...,
 termoSelected: false,
 terms: []
},
computed: {
    ...mapGetters({
      getPaymentUtils: 'negotiationaccount/getPaymentUtils', // It returns a Array
    })
},
mounted() {
 console.log(this.getPaymentUtils.rememberOptionsCash) // Shows data OK
 this.terms = Array.from(this.getPaymentUtils.rememberOptionsCash)
},
methods: {
 checkBoxChanged (index) { // Caled when checkbox is changed with v-model termoSelected
      this.terms[index].selected = this.termoSelected // Trigger: Error: [vuex] do not mutate vuex store state outside mutation handlers.
  }
}

}

我也试过.slice() 功能。但不起作用。所以我的问题是,当我使用 Getter 从 State 获取值时,无论如何我都无法复制数组。我该如何解决这个问题?

【问题讨论】:

  • 在您尝试复制该数组之前,您确定您的数组已加载并具有价值?
  • @AniketPawar 是的,我用我用来检查它的控制台进行了编辑
  • 我不知道 vuex,但我很确定我可以回答您是否可以将数组显示为 JSON 或将其登录到控制台时的样子。

标签: javascript arrays vue.js vuex


【解决方案1】:

在 typescript 和 ES6 中,您可以使用扩展运算符,例如:

this.terms = [...this.getPaymentUtils.rememberOptionsCash]

但根据数组中对象的深度,您需要使用 lodash 中的 deepClone 之类的东西。

【讨论】:

  • 也不起作用...使用 cloneDeep:'_' is not defined (no-undef)
  • 所以......一个丑陋的方法是做this.terms = JSON.parse(JSON.stringify(this.getPaymentUtils.rememberOptionsCash)),但它应该工作
  • 我的问题听起来mounted()方法没有按顺序执行
  • 你的错误'_' is not defined (no-undef)是因为你没有在你的项目中正确安装和导入lodash
  • JSON.parse(JSON.stringify(this.getPaymentUtils.rememberOptionsCash)) 工作正常。
【解决方案2】:

我经常使用的东西是这样的:

/**
 * Converts array-ish object to iterable.
 * This works with any object that follows these rules:
 *
 *  - `object` has a property `length` which is a positive integer or zero
 *  - for each integer `i` between 0 and `object.length`, there exists a property `object[i]`
 * @template T
 * @param {T[]|HTMLCollectionOf<T>|{length:number, [name:string]:T}} object
 * @returns {IterableIterator<T>}
 */
function* toIterable(object) {
    const l = object.length;
    for (let i = 0; i < l; ++i) {
        yield object[i];
    }
}

如果this.getPaymentUtils.rememberOptionsCash 遵循上述规则,该函数将为您提供一个迭代器。然后可以将其用于扩展以创建副本:

const asArray = [...toIterable(this.getPaymentUtils.rememberOptionsCash)];

我通常将它用于 HTML 集合和格式不正确的 JSON。它的好处是您可以在不复制数组的情况下进行迭代,例如:

for(const option of toIterable(this.getPaymentUtils.rememberOptionsCash)) {
    console.log(option);
}

如果上面的代码不起作用,请用this.getPaymentUtils.rememberOptionsCash 的实际外观示例更新您的帖子。从错误看来,您可能不允许以您访问它们的方式访问数组中的对象。

【讨论】:

  • 这是一道vuex的题,一定要知道vuex的状态资源。但基本上,我不能复制数组,你的函数也不起作用。
猜你喜欢
  • 2019-10-09
  • 2021-08-23
  • 2019-11-10
  • 1970-01-01
  • 2018-11-30
  • 2021-09-30
  • 2018-07-12
  • 2020-12-11
  • 2019-08-21
相关资源
最近更新 更多