source

데이터 속성을 Vuex getter에서 반환된 값으로 설정하는 방법

nicesource 2022. 10. 25. 17:37
반응형

데이터 속성을 Vuex getter에서 반환된 값으로 설정하는 방법

이전 컴포넌트에서 사용자가 클릭한 항목에 따라 데이터를 표시하는 Vue 컴포넌트가 있습니다.처음 클릭할 때 '현재' 인덱스를 설정합니다.다음 페이지로 넘어가면 데이터 어레이를 검색하여 '현재' 데이터를 반환하는 게터가 있습니다.

리디렉션되는 구성 요소는 사용자가 편집할 수 있는 양식입니다.최신 데이터를 미리 입력해 두고 싶습니다.플레이스 홀더가 아닌 실제 값으로 표시되므로 사용자가 직접 편집할 수 있습니다.

문제는 getter에서 반환된 값을 v-model로 바인딩할 수 있도록 데이터 함수 값으로 설정하는 방법을 모른다는 것입니다.

HTML

<input type="text" class="form-control" id="nickname1" v-model="name" name="name">
<input type="text" class="form-control" id="address1" placeholder="" v-model="address" name="address" > 
<input type="text" class="form-control" id="city1" placeholder="" v-model="city" name="city" > 

VUE

data: function() {
    return {
        name: this.currentArea.title,
        address: this.currentArea.address,
        city: this.currentArea.city,
        state: this.currentArea.state
    }
},
computed: {
    currentArea() { return this.$store.getters.currentArea }
}

* this.currentArea.title 및 currentArea.title은 작동하지 않습니다.

* 플레이스 홀더를 바인드하면 데이터가 올바르게 표시되므로 getter 함수가 currentArea를 올바르게 반환하고 있습니다.

data메서드는 초기화 중에 계산된 속성이 설정되기 전에 한 번만 실행됩니다.그래서 참고해서currentArea내부로부터data방법은 원래대로 되지 않는다undefined사형 집행 시.

한다면this.$store.getters.currentArea이 컴포넌트의 수명에는 변화가 없을 것으로 예상됩니다.데이터 속성을 설정하는 것이 가장 간단합니다.mounted후크:

data() {
  return {
    name: '',
    address: '',
    city: '',
    state: ''
  }
},
mounted() {
  let area = this.$store.getters.currentArea;
  this.name = area.name;
  this.address = area.address;
  this.city = area.city;
  this.state = area.state;       
} 

또는 이 컴포넌트의 데이터 속성이 항상 동일한 경우currentArea, 당신은 간단히 돌아올 수 있습니다.this.$store.getters.currentArea에서data직접 메서드:

data() {
  return this.$store.getters.currentArea;
}

@thanksd: 답변 감사합니다.상태가 vuex에 저장되어 컴포넌트에 일시적으로 불완전한 상태로 전송된 후 가져오기를 통해 업데이트되는 시나리오를 작업하고 있습니다.그리고 형태로 편집이 가능해야 합니다.

이 솔루션은 vuex에서 getter를 사용하여 상태의 일부를 내보내는 것이었습니다.

getters: {
  getItemDetail: (state, getters) => (id) => {
    let item = state.openedItems.items.find(i => i.id === id);
    return item ? item.data : null;
  }
}

데이터, 계산 및 감시 속성을 조합하여 컴포넌트에서 사용(및 lodash의 도움을 받아 객체를 심층 클로닝):

data () {
  return {
    itemDetail: null
  };
},
computed: {
  itemData () {
    return this.$store.getters.getItemDetail(this.item.id);
  }
},
watch: {
  itemData (n, o) {
    this.itemDetail = _.cloneDeep(n);
  }
}

마지막으로 입력을 "itemDetail"에 바인드합니다(이 예에서는 elemen 스위치를 사용합니다).

<el-switch v-model="itemDetail.property"></el-switch>

(하지만 Vue는 처음이지만) 저는 이 타협이 효과적이라고 생각합니다.

언급URL : https://stackoverflow.com/questions/44834822/how-to-set-data-properties-to-value-returned-from-vuex-getter

반응형