zidanow
zidanow

Reputation: 700

How can i fix “this is undefined” in VueJS?

The line this.$store.commit('disconnect'); is causing a "this is undefined" error, what can i do ?

store/index.js :

export const state = () => ({
  log: false,
  user: {token: null, id: null, username: null, email: null, created_at: null, pseudo: null}
})


export const mutations = {
  connect (state) {
    state.log = true
  },
  disconnect (state) {
    state.log = false,
    state.user.id = null,
    state.user.username = null,
    state.user.email = null,
    state.user.created_at = null,
    state.user.pseudo = null
  }
}

index.vue

<script>
import axios from "axios";

  methods: {
    async login() {
    var self = this;

    const auth_res = axios({
      method:'post',
      url:'http://127.0.0.1:8000/v2.0/auth',
      data:{
        username: this.username,
        password: this.password
      }
      }).then(function(res){
        this.$store.commit('disconnect');
        self.$router.push('/');
      }).catch(function (erreur) {
        console.log(erreur);
      });
    }
  }
}
</script>

If i delete the line of the commit in the index.vue file, it works fine, but i need to use it so how can i fix this ?

Thanks again

Upvotes: 0

Views: 1437

Answers (1)

Kiran Maniya
Kiran Maniya

Reputation: 9009

In the callback context, this tense to callback itself. That's why you are getting the error. You should replace it with,

self.$store.commit('disconnect');

where the self holds the actual context of Vue. Here is the explanation,

methods: {
    async login() {
    var self = this; // You got the context of the method which belongs to Vue

    const auth_res = axios({
      method:'post',
      ...
      }).then(function(res){
        self.$store.commit('disconnect'); // The self.$store is now avaialable in callback
        self.$router.push('/');
      }).catch(function (erreur) {
        ...
      });
    }
  }

Upvotes: 2

Related Questions