什么会影响 Vue 计算属性是否重新计算? [英] What is affecting on will Vue computed property re-computed or no?

查看:70
本文介绍了什么会影响 Vue 计算属性是否重新计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每次 selectedOptionsIndexes 改变时都会重新计算 currentSelectionViewContent.真的,有时它有效,有时 - 无效.

I expect that currentSelectionViewContent will be re-computed each time when selectedOptionsIndexes has changed. Really, sometimes it works, sometimes - not.

import { Component, Prop, Vue, Watch } from "vue-property-decorator";

@Component({
  template
})
export class SelectField extends Vue {

  private onNewOptionSelected(newOption: SelectField.Option, indexInArray: number): void {

    console.log("~~~~~~~~~~~~~~~");
    console.log(JSON.stringify(this.selectedOptionsIndexes, null, 2));

    this.selectedOptionsIndexes[0] = indexInArray;

    console.log(JSON.stringify(this.selectedOptionsIndexes, null, 2));
    console.log("--------------");

    if (isUndefined(newOption.key)) {
      this.$emit("change", newOption.relatedEntity);
    } else {
      this.$emit("change", newOption.key);
    }
  }

  // Vue computed property in "vue-property-decorator" syntax
  private get currentSelectionViewContent(): string {
    console.log("Recomputing ...");
    switch (this.selectedOptionsIndexes.length) {
      case 0:
        return SelectField.DEFAULT_NOTHING_SELECTED_PLACEHOLDER;
      case 1:
        return this.selectOptions[this.selectedOptionsIndexes[0]].title;
      default:
        return SelectField.DEFAULT_MULTIPLE_OPTIONS_SELECTED_LETTERING;
    }
  }
}

工作案例:

不工作的情况(无需重新计算):

Not working case (no re-computing):

我很抱歉没有为这种情况创建复制(复制导致此问题的组件,它的依赖关系和环境)花费了太长时间.如果没有repro你不明白这里有什么问题,请教我是什么影响了Vue的计算属性是否会重新计算.

I sorry about was not created the repro for this case (the reproducing of component where this problem causes, it's dependencies and also environment) takes too long time. If you can not understand what wrong here without repro, please just teach me what is affecting on will Vue computed property re-computed or no.

推荐答案

Vue 在数组方面有一些需要注意的行为.来自文档:

Vue has certain behavior around arrays to be aware of. From the docs:

Vue 无法检测到数组的以下更改:

Vue cannot detect the following changes to an array:

  • 当您直接使用索引设置项目时,例如vm.items[indexOfItem] = newValue
  • 当您修改长度时数组,例如vm.items.length = newLength

为确保 Vue 看到您的数组更改,请始终复制该数组并重新分配,如下所示:

To ensure Vue sees your array change, always make a copy of the array and re-assign it, like this:

var updatedIndexes = [...this.selectedOptionsIndexes]; // Copies array
updatedIndexes[0] = indexInArray; // Update the copy
this.selectedOptionsIndexes = updatedIndexes; // Overwrite with copy

这篇关于什么会影响 Vue 计算属性是否重新计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆