vue中同一个方法中发送axios请求获取参数值不同

toUpdateCar() {
	if (this.checked.length != 1) {
		alert("只能选择一项信息进行修改!")
		$("#update").attr("data-toggle", "");
	} else {
		$("#update").attr("data-toggle", "modal");
		$("#carNo").attr("disabled", "disabled");
		axios.get("http://localhost:8080/carInfo?cid=" + this.checked[0])
			.then(response => {
				this.car.id = response.data.car.id;
				this.car.carNo = response.data.car.carNo;
				this.car.carBrand = response.data.car.carBrand;
				this.car.carModel = response.data.car.carModel;
				console.log("carBrand1="+this.car.carBrand);
			})
		console.log("carBrand2="+this.car.carBrand);
		this.checked = [];
	}
},

当定义的变量在axios请求中时,可以获取值,而在axios外再次输出该变量则无法获取

  • 原因:变量在axios响应中获取值,但axios中取得的响应值没有马上赋值给定义的变量,所以第二次输出定义的变量时,变量还没有被响应值赋值,所以输出的值为空

  • 解决办法:

    在axios中声明一个方法,在该方法中调用变量

    toUpdateCar() {
    	if (this.checked.length != 1) {
    		alert("只能选择一项信息进行修改!")
    		$("#update").attr("data-toggle", "");
    	} else {
    		$("#update").attr("data-toggle", "modal");
    		$("#carNo").attr("disabled", "disabled");
    		axios.get("http://localhost:8080/carInfo?cid=" + this.checked[0])
    			.then(response => {
    				this.car.id = response.data.car.id;
    				this.car.carNo = response.data.car.carNo;
    				this.car.carBrand = response.data.car.carBrand;
    				this.updateModelList();
    		})
    	this.checked = [];
    	}
    },
    updateModelList(){
    	axios.get("http://localhost:8080/findModelByBid?bid="+this.car.carBrand)
    		.then(response=>{
    			this.carModelList = response.data.carModelList;
    		})
    	},
    
posted @ 2021-08-06 16:56  江亭夕望  阅读(350)  评论(1)    收藏  举报