Vue.js Ajax调用未将更改映射到基础html表

时间:2019-11-25 09:58:54

标签: javascript vue.js axios

我正在使用vuejs和axios进行简单的ajax调用:

var app1 = new Vue({
  el: '#app1',
  data: {
    test: []
  },
  methods: {    
    setAJAX: function () {
      axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
    }
  }
});

这为什么起作用:

setAJAX: function () {
      axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
    }

但这不起作用,更改未映射到表中(this.test未定义):

setAJAX: function () {
      axios.get('/Departments/GetDepartments/').then(function(response){this.test = response.data.listBACAET});
    }

1 个答案:

答案 0 :(得分:4)

这是由于箭头功能的工作方式:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

使用箭头函数时,this隐式绑定到封闭范围的this,在您的情况下,该范围是调用该方法的vue实例。 因此,您正在设置视图模型的数据,该数据有效。

使用std时。函数,范围内没有this,因此会出现错误。要使用性病。函数,您需要像这样为视图模型定义一个闭包:

setAJAX: function () {
  let vm = this
  axios.get('...').then( function(response) {
    vm.test = response.data.listBACAET
  });
}