我正在为我的应用程序中的某些组件制作一个加载器。
这是我的组件:
mounted() {
this.loading = true;
this.getProduct();
},
methods: {
async getProduct() {
await this.$store.dispatch('product/getProducts', 'bestseller');
console.log(123);
this.loading = false;
}
},
Vuex Action :
getProducts({commit}, type) {
axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
问题出在这一行:await this.$store.dispatch('product/getProducts', 'bestseller');
我希望代码会在该行停止并等待从 AJAX 调用加载数据,然后将加载设置为 false
;
但事实并非如此。加载仍然设置为 false
并且 console.log
在我的数据准备好之前运行。
我已经尝试将 async/await 移动到 Vuex 操作中并且它起作用了。但是,我没有弄清楚它们之间的区别。
下面的代码适合我:
组件:
mounted() {
this.loading = true;
this.$store.dispatch('product/getProducts', 'bestseller').then((res) => {
this.loading = false;
});
},
Vuex Action :
async getProducts({commit}, type) {
let res = await axios.get(`/api/products/${type}`);
commit('SET_PRODUCTS', {products: res.data, type});
}
最佳答案
改变这个:
getProducts({commit}, type) {
axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
对此:
getProducts({commit}, type) {
return axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
应该可以。
axios.get
返回一个 promise 。您需要返回该 promise ,以便让 await
等待它。否则,您将隐式返回 undefined
并且 await undefined
将立即解析。
关于javascript - 异步/等待 Vuex 调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700815/