sourcecode

Vue Vuex: 계산된 속성이 변경되기 전에 오래된 데이터가 일정 기간 유지됩니다.

copyscript 2022. 8. 8. 19:59
반응형

Vue Vuex: 계산된 속성이 변경되기 전에 오래된 데이터가 일정 기간 유지됩니다.

처음입니다vuex아직도 너무 많이 쓰고 있어요.예를 들어, 나는product내 목록store상태. 내가 봤을 때)product나는 만든다axios그것과 함께 전화하다product.id제품 데이터를 커밋하여currentProduct다른 제품을 보면, 그 페이지는 다음과 같이 렌더링 됩니다.currentProduct먼저 이전 데이터를 기술한 다음, 다음 데이터를 기술합니다.action commits그런 다음 새로 가져온 항목으로 업데이트됩니다.currentProductvue가 내 뷰 데이터를 새 데이터로 변경합니다.user오래된 데이터가 새로운 데이터로 대체되는 것을 명확하게 알 수 있습니다.그러나 새로운 데이터가 커밋된 후에만 페이지를 로드하고 싶다.state.

`store.js`

state :{
    productList:{},
    currentProduct:{
     id:'',name:'',price:'','seller'
    }
},
mutations:{
    UPDATE_CURRENT_PRODUCT : (state, data) =>{
     state.currentProduct = Object.assign({},state.currentProduct, data);
    }

},
actions:{
    fetchProducts(){
     const response = fetch...... // logic to fetch product
     commit('UPDATE_CURRENT_PRODUCT', response.data);
    }
}

내 렌더링 페이지:

이 페이지에는 내 제품 목록이 표시됩니다.

'productList.vue'

<div v-for="product in productList" @click="viewProduct(product.id)">
    <p>{{product.name}}</p>
</div>

computed(){

    ...mapState(['productList'])

},
methods:{
    viewProduct(product_id){
        this.$store.state.dispatch('fetchProducts', product_id);
    }
}

이 페이지에서는 특정 제품의 뷰를 렌더링합니다.

`product.vue`

<div>
    <p>{{currentProduct.name}}</p>
</div>

computed(){

    ...mapState(['currentProduct'])

}

인마이product.vue첫 번째 오래된 데이터가 표시되고 얼마 후 새 데이터가 교체됩니다.뭔가 빠진 것 같아..오래된 데이터가 새로운 데이터로 대체되는 것을 보지 않고 새로운 데이터를 직접 보고 싶습니다.다른 방법이 있나요?vuex

주요 내용은 다음과 같습니다.

새 데이터가 내 상태로 커밋된 후에만 페이지를 로드하고 싶다.

비동기 방식을 서로 따르게 할 필요가 있습니다.그것을 하는 멋진 방법이 있다.

내 생각엔fetchProducts()공리학자들은 데이터를 입수/투고한다.공리는 약속을 기반으로 하기 때문에, 당신은 약속을 가지고 돌아올 수 있습니다.

fetchProducts() {
 return axios.get('/get/some/data')
    .then(r => { // commit and stuff
     })
    .catch(e => { // error handling
     })
}

그러면 쉽게 할 수 있습니다.

this.$store.state.dispatch('fetchProducts', product_id)
 .then(r=> {if(r){ // get the data from vuex 
 } else { // error
 })
 .catch(e => {});

디스패치의 다음 단계는 축의 다음 단계입니다.(예를 들어, 연속적으로 실행할 필요가 있는 2개의 Axi call이 있는 경우, 첫 번째 방법으로 두 번째 Axi call을 호출하면 문제가 해결됩니다.)

이해해주셨으면 좋겠습니다.:)

간단한 해결책은 작업이 로드/디스패치될 때 데이터를 초기값으로 재설정하는 것입니다.

여기서 코드를 편집해 보겠습니다.

actions:{
    fetchProducts(){
     const response = fetch...... // logic to fetch product
     commit('UPDATE_CURRENT_PRODUCT', response.data);
    }
}

이를 위해:

actions:{
    fetchProducts(){
     // Add below line to reset the state when loading.
     commit('UPDATE_CURRENT_PRODUCT', null);
     /***********************************************/
     const response = fetch...... // logic to fetch product
     commit('UPDATE_CURRENT_PRODUCT', response.data);
    }
}

저는 위의 솔루션이 효과가 있었습니다.이 방법이 당신이나 다른 사람에게도 효과가 있기를 바랍니다.

이 경우 새 데이터가 검색된 후에만 컴포넌트가 업데이트되도록 비동기 대기 기능을 사용해야 합니다.

async fetchProducts(){
    await const response = fetch...... // logic to fetch product
    commit('UPDATE_CURRENT_PRODUCT', response.data);
   }

viewProduct 메서드에서도 마찬가지입니다.상세한 것에 대하여는, 다음의 링크(페이지의 마지막 예)를 참조해 주세요.https://vuex.vuejs.org/guide/actions.html

언급URL : https://stackoverflow.com/questions/54454602/vue-vuex-old-data-remains-for-some-time-before-computed-property-changes

반응형