为什么我得到,无法设置未定义的属性

时间:2019-12-02 22:17:19

标签: javascript vue.js nuxt.js

我正在使用 nuxt js axios 进行小型项目,我尝试将响应数据放入我的{{1} }对象,但我在控制台中收到未定义的错误消息,因为您已经在数据中声明了formFields,如您所见:

这是我的代码:

formFields

我的数据变量:

editCustomers (customerId, submit = false) {
  this.editMode = true
  this.customerId = customerId
  if (submit === 1) {
    // this.$Progress.start()
    this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {
      this.validation(data)
      // another form validation again using the helper
      this.refresh = true
    })
    // this.$Progress.finish()
  } else {
    this.$axios.$get('mydomain.com' + customerId).then(function (data) {
      this.formFields = data.customers[0]
    })
  }
}

如您所见,我已经声明了数据,但是当我这样做时data () { return { laravelData: {}, formFields: {}, search: null, editMode: true, customerId: null, refresh: false } } 我收到此错误消息:

this.formFields = data.customers[0]

2 个答案:

答案 0 :(得分:1)

在JavaScript中,this指当前范围的当前目标,当使用function关键字声明函数时,this指的是调用该函数的对象

您编写代码的方式this不再引用Vue实例,this引用undefined(因为回调可能是在没有this的情况下调用的arg),请尝试在函数外部捕获this并将其包含在其闭包中:

editCustomers (customerId, submit = false) {
  this.editMode = true
  this.customerId = customerId
  const vm = this; // vm = this = Vue instance
  if (submit === 1) {
    // this.$Progress.start()

    this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {
      // vm = Vue instance; this = undefined
      vm.validation(data)
      // another form validation again using the helper
      vm.refresh = true
    })
    // this.$Progress.finish()
  } else {
    this.$axios.$get('mydomain.com' + customerId).then(function (data) {
      // vm = Vue instance; this = undefined
      vm.formFields = data.customers[0]
    })
  }
}

ETA: 为了更好地理解这一点:

function myName() { return this.name};
var obj = {name:'test'};
var objName = myName.bind(obj); // a new function where the `this` arg is bound to `obj`
var text = objName(); // text === 'test'
console.log(text);

答案 1 :(得分:1)

只需更改此部分:

this.$axios.$get('mydomain.com' + customerId).then(function (data) {
  this.formFields = data.customers[0]
})

对此:

this.$axios.$get('mydomain.com' + customerId).then((data) => {
  // Now you can access your class instance
  this.formFields = data.customers[0]
})