Search code examples
javascriptrestvue.jsaxiosvue-cli-3

Axios - cannot change variable data value


I tried to change the variable data using axios, i am using vue-axios and vue cli 3.

This is the code:

const qs = require('qs')
export default {
  name: 'Home',
  data: function () {
    return {
      email: null,
      errEmail: false,
      baseUrl: 'https://www.example.com/isemail.php'
    }
  },
  methods: {
    next: function () {
    },
    err: function () {
      this.axios.post(this.baseUrl + 'functions/isEmail.php', qs.stringify({
        value: this.email
      }))
        .then(function (resp) {
          this.errEmail = true
        })
    }
  }
}
<div v-if="errEmail">Target Success</div>

Actually i am trying change the errEmail variable depend on the server callback like this:

this.errEmail = resp.data.isemail

but using constant seems not working too.


Solution

  • Change this

    .then(function (resp) {
      this.errEmail = true
    })
    

    to this

    .then((resp) => {
      this.errEmail = true
    })
    

    Or manually bind this

       .then(function (resp) {
          this.errEmail = true
        }.bind(this))