【问题标题】:Unable to access this keyword property inside a vuejs promise [duplicate]无法在 vuejs 承诺中访问此关键字属性 [重复]
【发布时间】:2017-11-20 18:46:00
【问题描述】:

我正在执行异步验证,我需要在 vuejs 中全局访问 $axios 集,但这失败了

    Validator.extend('async_validate_job_type', {
    getMessage: field => `The Name already exists`,
    validate: value => new Promise((resolve) => {
        //validate email.
        this.$axios.post('/validate/position-type', {email:value})
            .then(
               ....perform stuff here
            )

    })
});

现在上面抛出一个错误

cannot read propery post of undefined

在其他组件中使用this.$axios.post 有效。但在上面似乎我无法访问 this.$axios。我哪里错了?

我已经通过 axios 设置了

Vue.prototype.$axios =  axios.create(axiosConfig);

同样使用像这样的正常功能也会失败

    Validator.extend('async_validate_job_type', {
    getMessage: field => `The Name already exists`,
    validate(value){
      return new Promise((resolve) => {
          console.log("value of this is", this); //this is undefined
          this.$axios.post())


      })
    }
});

【问题讨论】:

  • 我只是将 axios 发送到 window,而不是添加到 Vue 原型中。但是,我猜你有一个范围问题,this 实际上是指窗口而不是 Vue 实例。尝试使用普通函数:validate(value) { return new Promise(...)}
  • 在普通函数中调用 this 也会失败
  • @craig_h ive 用非正常函数尝试更新了同样失败的问题

标签: javascript vue.js vuejs2 axios


【解决方案1】:

要在 VueComponent 实例中添加一些东西,请使用 mixins:

Vue.mixin({
  beforeCreate: function () {
    this.$axios = axios.create(axiosConfig);
  }
});

文档: https://vuejs.org/v2/guide/mixins.html#Global-Mixin

示例: https://jsfiddle.net/4y0ftc51/

【讨论】:

    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2017-01-30
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多