无法在vuejs promise中访问此关键字属性

时间:2017-11-20 18:46:00

标签: javascript vue.js vuejs2 axios

我正在执行异步验证,我需要在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的其他组件中工作。但在上面似乎我无法访问这个。$ 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())


      })
    }
});

1 个答案:

答案 0 :(得分:-2)

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

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

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

实施例: https://jsfiddle.net/4y0ftc51/

相关问题