我正在为我的应用程序中的一些组件制作加载器。
这是我的组件:
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 action中,并且它起作用了。但是,我不明白它们之间的区别。
下面的代码已经对我起作用:
组件:
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});
}