首页 > 解决方案 > Vue Vuex:在计算属性更改之前,旧数据会保留一段时间

问题描述

我是新手vuex,但我仍然过度使用它。例如,我在我的州有一个product清单。store当我查看一个时,productaxios用它打电话product.id并将产品数据提交到currentProduct状态。然后,如果我查看另一个产品,则页面首先以状态呈现,currentProduct即旧数据,然后在我的action commits.. 之后将其更新为新获取的currentProduct,然后 vue 将我的视图数据更改为新数据。可以清楚地看到旧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

标签: vue.jsvuejs2vue-componentvuex

解决方案


关键部分是:

我只想在新数据提交到我的状态后加载页面

您想让异步方法彼此跟随。有一种很酷的方法可以做到这一点。

我猜在fetchProducts()axios 中获取/发布数据。因为 axios 是基于 promise 的,所以你可以带着它返回。

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 => {});

调度的 then 在轴的 then 之后运行。(例如:如果有两个axios调用必须顺序运行,可以在第一个的then方法中调用第二个,就可以解决问题了。)

我希望你明白这一点。:)


推荐阅读