在使用vue时有时候我们会需要调用一个方法获得该方法的返回值,然后将该返回值传到另外一个方法作为参数。但当我们实践后会发现第一个方法的值根本传不出去。比如以下代码
addImg() {
const formData = new FormData();
const fileInput = document.querySelector('#file-input');
const file = fileInput.files[0];
formData.append('file', file);
console.log("2."+this.form.food_image)
axios.post('/food/images/upload',formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
let result = response.data;
this.form.food_image = result.message;
console.log("3."+this.form.food_image)
})
.catch(err => {
alert(err);
});
console.log("4."+this.form.food_image)
},
updateFoodDesc(){
if (document.querySelector('#file-input').files.length != 0) {
console.log("1."+this.form.food_image)
this.addImg();
console.log("5."+this.form.food_image)
}
this.foodType();
axios.post('/food/foods/updateFoodDesc',this.form)
.then(response => {
let result=response.data;
})
.catch(err => {
alert(err);
});
},
简述:
这是一个修改信息的方法,而在修改所有信息之前需要先修改图片然后返回图片名字,再一起写入到form中
进行所有信息的修改。这时候就惠发现问题
思路:
我在每一个this.form.food_image值可能更改的地方都加了console.log以便更为确切的观察值的变化,按照我们所想的应该是正确无误的取到了所更改的this.form.food_image的值也就是console.log(“5.”+this.form.food_image)会正确打印我们所上传的图片名称,但是事实真的如此吗?
下载是我们原先的图片,cat1是我们所要更改的图片,我们可以发现food_image并没有根据我们预想的进行变化,food_image只在then方法中真确变化,出了then他的值并没有进行变化。
原因:
其实我们观察序号的打印顺序就可以发现问题所在,按照我们所想的5应该是最后打印的,但事实是3是最后打印的。这是因为axios中的方法是异步方法,并不是严格按照顺序进行的,所以3才会在最后进行打印
解决办法:
我们可以使用async/await解决异步问题,async/await字如其名作用就是等待await所修饰的方法执行完才会进行下一步。
具体代码实现
addImg() {
const formData = new FormData();
const fileInput = document.querySelector('#file-input');
const file = fileInput.files[0];
formData.append('file', file);
console.log("2."+this.form.food_image)
try {
const response = await axios.post('/food/images/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
let result = response.data;
this.form.food_image=result.message
console.log("3."+this.form.food_image)
} catch (e) {
alert(e)
}
console.log("4."+this.form.food_image)
},
async updateFoodDesc(){
if (document.querySelector('#file-input').files.length != 0) {
console.log("1."+this.form.food_image)
await this.addImg();
console.log("5."+this.form.food_image)
}
this.foodType();
axios.post('/food/foods/updateFoodDesc',this.form)
.then(response => {
let result=response.data;
})
.catch(err => {
alert(err);
});
},
这个时候我们就会发现按照我们所想的顺序执行了,数据也成功更改了。