vue.js - 即使与方法处于同一级别,创建和挂载的 Vuejs 也无法正常工作
问题描述
我在使用Vue.jscreated()
和mounted()
使用 Vue.js时遇到了奇怪的行为。我需要设置 2 个列表created()
- 所以这意味着这 2 个列表将帮助我创建第三个列表,它是一个合并。
这是代码:
// return data
created () {
this.retrieveSellOffers();
this.getAllProducts();
},
mounted () {
this.mergeSellOffersProducts();
},
methods: {
retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
SellOfferServices.getAllBySellerId(this.sellerId)
.then((response) => {
this.sellOffers = response.data;
console.log("this.sellOffers");
console.log(this.sellOffers);
})
.catch((e) => {
console.log(e);
});
},
getAllProducts() {
ProductServices.getAll()
.then((response) => {
this.products = response.data;
console.log("this.products");
console.log(this.products);
})
.catch((e) => {
console.log(e);
});
},
mergeSellOffersProducts () {
console.log(this.products) // print empty array
console.log(this.sellOffers) // print empty array
for (var i = 0; i < this.sellOffers.length; i++) {
if (this.sellOffers[i].productId === this.products[i]._id) {
this.arr3.push({id: this.sellOffers[i]._id, price: this.sellOffers[i].price, description: this.products[i].description});
}
}
this.arr3 = this.sellOffers;
},
}
//end of code
所以我的问题是当我输入时mergeSellOffersProducts()
,我的 2 个列表是空数组:/
编辑 :
这种方式对我有用:
async mounted() {
await this.retrieveSellOffers();
await this.getAllProducts();
this.mergeSellOffersProducts();
},
methods: {
async retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
this.sellOffers = (await axios.get('link/api/selloffer/seller/', { params: { sellerId: this.sellerId } })).data;
},
async getAllProducts() {
this.products = (await axios.get('link/api/product')).data;
},
}
解决方案
- 我认为原因是:Vue在继续组件生命周期之前不会等待Promise 解决。
- 您的函数retrieveSellOffers()和getAllProducts()包含 Promise 所以也许您必须在created()钩子中等待它们:
async created: {
await this.retrieveSellOffers();
await this.getAllProducts();
}