如何避免计算属性中的意外副作用-VueJS

时间:2020-03-20 13:48:59

标签: forms vue.js vuex

我正在尝试用vuex商店中的数据预填充表单,在提供的代码中是期望的结果,我需要,但我知道这不是做到这一点的方法。我是Vue / Vuex的新手。输入使用v模型,这就是为什么我不能使用:value="formInformation.parentGroup"进行预填充的原因。

  data() {
    return {
      groupName: { text: '', state: null },
      parentName: { text: '', state: null },
    };
  },
  computed: {
    formInformation() {
      const groups = this.$store.getters.groups;
      const activeForm = this.$store.getters.activeForm;
      if (activeForm.groupIndex) {
        const formInfo = groups[0][activeForm.groupIndex][activeForm.formIndex]
        this.groupName.text = formInfo.name // Is there a way to not use this unexpected side effect ?
        return formInfo;
      } else {
        return 'No Form Selected';
      }
    },
  },

我已经搜索了很长时间了,所以我只需要问一下。也许我只是在寻找错误的地方,但也许有人可以帮助我。

3 个答案:

答案 0 :(得分:1)

您做得很好,只需进行一些重构和分离-将所有逻辑与计算的属性分离(您也可以使用mapGetters):

  mounted() {
    if (this.formInformation) {
      this.$set(this.groupName.text, this.formInformation.name);
    }
  },
  computed: {
    groups() {
      return this.$store.getters.groups;
    },
    activeForm() {
      return this.$store.getters.activeForm;
    },
    formInformation() {
      if (this.activeForm.groupIndex) {
        return this.groups[0][this.activeForm.groupIndex][
          this.activeForm.formIndex
        ];
      }
    }
  }

答案 1 :(得分:0)

您可以将groupName设为计算属性:

computed: {
    groupName() {
         let groupName = { text: '', state: null };
         if (formInformation.name) {
          return groupName.text = formInfo.name;
         }
         return groupName;
    }

或者您可以在formInformation上设置观察者:

watch: {
    formInformation: function (newFormInformation, oldFormInformation) {
      this.groupName.text = formInfo.name;
    }
  },

答案 2 :(得分:0)

避免在data property中更改computed

Computed用于对reduce属性进行某些操作(例如filterdata等),而只是对return进行{

相反,您可以尝试

result