vue.js - Vue Vuex:在计算属性更改之前,旧数据会保留一段时间
问题描述
我是新手vuex
,但我仍然过度使用它。例如,我在我的州有一个product
清单。store
当我查看一个时,product
我axios
用它打电话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
解决方案
关键部分是:
我只想在新数据提交到我的状态后加载页面
您想让异步方法彼此跟随。有一种很酷的方法可以做到这一点。
我猜在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方法中调用第二个,就可以解决问题了。)
我希望你明白这一点。:)
推荐阅读
- python - Django:检查 Django-admin 表单中的数据
- powerbuilder - 如何一次同时滚动两个数据窗口?
- php - xdebug 扩展不随 php:5.6-apache 一起安装
- c# - 在特定格式的标签中显示计时器间隔刷新
- laravel-5 - 为什么 Grammar::parameterize 添加新的设置行
- angular - 如何在父组件提交按钮上获取模板驱动的表单数据
- r - 如何在ggplot2中添加平均值和中位数的图例?
- hadoop - 将 Presto 添加为 Grafana 的数据源
- qt - QWidget中的QT MouseMove模拟不起作用
- python - 无法在 keras 中生成张量板