解决办法
Ajax请求外定义变量
let _this=this;
Ajax请求内使用该变量调用Vue实例的数据
_this.数据名=要修改的值
错误的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/vue.js"></script>
<script src="https://cdn.staticfile.org/vue-router/2.7.0/vue-router.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>
<body>
<div id="app" style="margin-left: 20%;margin-top: 10%">
<p>传递的数据:<span style="color: red">{{myInfo}}</span></p>
<p>输入水果的信息:</p>
编号:<input type="text" v-model="fruitId"/>
名称:<input type="text" v-model="fruitName"/>
数量:<input type="text" v-model="fruitNum"/>
<button @click="submitData">提交</button>
</div>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
fruitId: 1,
fruitName: '苹果',
fruitNum: 3,
myInfo: '这里显示传递的数据'
},
methods: {
submitData: function () {
axios
.post('https://www.zoutl.cn/getFruitJson2?id=' + this.fruitId + '&name=' + this.fruitName + '&num=' + this.fruitNum + '')
.then(function (response) {
let id = response.data.id;
let name = response.data.name;
let num = response.data.num;
this.myInfo = "编号:" + id + ",名称:" + name + ",数量:" + num;
})
.catch(function (error) {
console.log(error);
});
}
}
})
</script>
</body>
</html>
点击提交按钮后,红色字体内容不改变
修改后
修改methods内的submitData方法
methods: {
submitData: function () {
let _this = this;
axios
.post('https://www.zoutl.cn/getFruitJson2?id=' + this.fruitId + '&name=' + this.fruitName + '&num=' + this.fruitNum + '')
.then(function (response) {
let id = response.data.id;
let name = response.data.name;
let num = response.data.num;
_this.myInfo = "编号:" + id + ",名称:" + name + ",数量:" + num;
})
.catch(function (error) {
console.log(error);
});
}
}
点击提交按钮后,红色字体内容改变