Johnny John Boy
Johnny John Boy

Reputation: 3202

VueJS Axios Post Request - Can't update data binding

I am trying to update my VueJS page with the following method. To demonstrate where it works and where it doesn't I added explanation below but I am stuck how to bind the data.

<script>
      window.app = new Vue({
        el: '#app',
        data: {
          form: {
            email: '',
            password: ''
          },
          token: ''
        },
        methods: {
          onSubmit(e) {
                  e.preventDefault();
                  this.token = "This works!"
                  // alert(JSON.stringify(this.form))
                  axios.post('http://localhost:5000/login', {
                      username: this.form.email,
                      password: this.form.password
                  })
                  .then(function (response) {
                      // this.token = response.data.access_token
                      this.token = "This does not work!"
                      console.log(response);
                  })
                  .catch(function (error) {
                      console.log(error);
                  });
          },
          onReset(e) {
            e.preventDefault()
            // Reset our form values
            this.form.email = ''
            this.form.password = ''
          }
        }
      })
    </script>

Upvotes: 0

Views: 346

Answers (1)

ittus
ittus

Reputation: 22393

this.token inside function is not Vuejs instance. You should use arrow function for it

onSubmit(e) {
    e.preventDefault();
    this.token = "This works!"
    axios.post('http://mydomain/login', {
        username: this.form.email,
        password: this.form.password
    })
    .then((response) => {
        this.token = "This does not work!"
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
}

Upvotes: 3

Related Questions