vue js中this引用有时失败的原因
<script>
new Vue({
el:"#app",
data() {
return {
arr:[],
ShowArr:false,
}
},
created:function () {
this.getData();
},
methods:{
getData(){
axios.get("/data").then(function(res){
this.arr = res.data;
});
},
}
});
</script>
在这段代码中this引用实际上是指向的并非是Vue对象,而是发送请求的axios对象,也就是在这段代码执行之后,不能实现arr数据的刷新,要解决问题首先的在axios外部保存Vue的this引用,即:
methods:{
getData(){
var self = this;
axios.get("/data").then(function(res){
self.arr = res.data;
});
},
}
浙公网安备 33010602011771号