1

Am performing an async validation where i need to access the $axios set globally in vuejs but this fails

    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
            )

    })
});

Now the above throws an error

cannot read propery post of undefined

In other components using this.$axios.post works. But in the above seems i cannot access this.$axios. Where am i going wrong?

I have already setup axios via

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

Also using normal function like this also fails

    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())


      })
    }
});
Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 1
    I would just axios to `window`, rather than adding in to the Vue prototype. However, I would guess that you have a scoping issue and that `this` is actually referring to window and not a Vue instance. Try using a normal function instead: `validate(value) { return new Promise(...)}` – craig_h Nov 20 '17 at 19:00
  • calling this inside a normal function also fails – Geoff Nov 20 '17 at 19:17
  • @craig_h ive updated the question withnnormal function try which also fails – Geoff Nov 20 '17 at 19:19

1 Answers1

-3

To add something in VueComponent instance use mixins:

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

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

Example: https://jsfiddle.net/4y0ftc51/

tony19
  • 125,647
  • 18
  • 229
  • 307
Wszerad
  • 36
  • 3