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;
    });
  },
}

posted @ 2021-12-06 18:03  小宋的学习笔记  阅读(445)  评论(0)    收藏  举报