【发布时间】:2019-09-06 02:56:04
【问题描述】:
我正在为我的应用中的一些组件制作加载器。
这是我的组件:
mounted() {
this.loading = true;
this.getProduct();
},
methods: {
async getProduct() {
await this.$store.dispatch('product/getProducts', 'bestseller');
console.log(123);
this.loading = false;
}
},
Vuex 动作:
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 动作:
async getProducts({commit}, type) {
let res = await axios.get(`/api/products/${type}`);
commit('SET_PRODUCTS', {products: res.data, type});
}
【问题讨论】:
标签: javascript vue.js async-await vuex