programing

계산된 속성에서 예기치 않은 부작용을 방지하는 방법 - VueJs

prostudy 2022. 4. 12. 22:27
반응형

계산된 속성에서 예기치 않은 부작용을 방지하는 방법 - VueJs

나는 양식에 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';
      }
    },
  },

나는 지금 너무 오랫동안 앙와르를 찾아다녔기 때문에 그것을 물어볼 필요가 있었다.어쩌면 내가 뭔가 잘못된 것을 구글로 검색하는 것일 수도 있지만, 여기 있는 누군가가 나를 도와줄 수 있을지도 몰라.

당신은 잘 하고 있다. 약간의 리팩터링과 분리가 필요하다 - 계산된 속성에 대한 모든 논리를 분리한다(또한 사용할 수 있다).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
        ];
      }
    }
  }

당신은 만들 수도 있다.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;
    }
  },

돌연변이를 피하십시오.data propertycomputed.

Computed어떤 수술을 하도록 되어 있다(예: reduce,filter에 관하여data속성 & 단순함returnresult.

대신 다음을 시도해 보십시오.

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 // <-- [1] simply, remove this
      return formInfo;
    } else {
      return 'No Form Selected';
    }
  }
},

// [2] add this, so on change `formInformation` the handler will get called
watch: {
 formInformation: {
  handler (old_value, new_value) {
   if (new_value !== 'No Form Selected') { // [3] to check if some form is selected 
    this.groupName.text = new_value.name // [4] update the data property with the form info
   },
   deep: true, // [5] in case your object is deeply nested
  }
 }
}

참조URL: https://stackoverflow.com/questions/60775475/how-to-avoid-unexpected-side-effect-in-computed-properties-vuejs

반응형