三种写法
以下有三种写法,注意 第一种 的坑!!!其余两种任意采用一种皆可。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pay attention to this when using Axios in Vue.</title>
</head>
<body>
<div id="app">
<input type="button" value="this get请求" @click="thisGet">
<input type="button" value="self get请求" @click="selfGet">
<input type="button" value="other get请求" @click="otherGet">
<input type="text" v-model="text">
</div>
<!-- development version, includes helpful console warnings -->
<!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
text: 'test',
url: 'http://localhost/api/test',
},
methods: {
// fail
thisGet(){
console.log('thisGet-start');
console.log('origin:'+this.text);
axios.get(this.url).then(
function(res){
console.log(res.status);
this.text = 'thisGet:'+res.status;
console.log('thisGet-end:'+this.text);
}
);
},
// success
selfGet(){
console.log('selfGet-start');
console.log('origin:'+this.text);
let self = this;
axios.get(self.url).then(
function(res){
console.log(res.status);
self.text = 'selfGet:'+res.status;
console.log('selfGet-end:'+self.text);
}
);
},
// success
otherGet(){
console.log('otherGet-start');
console.log('origin:'+this.text);
axios.get(this.url).then((res) => {
console.log(res.status);
this.text = 'otherGet:'+res.status;
console.log('otherGet-end:'+this.text);
},function(error) {
console.log(error);
}
);
},
},
});
</script>
</body>
</html>
测试结果
箭头函数与 关键词function的区别
参考:https://blog.youkuaiyun.com/github_38851471/article/details/79446722