Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex: Cannot read property '$store' of undefined [duplicate]

I have set up a store in vue.js and can access the state parameters in the computed part of a compoenent:

computed: {
    BASE_URL () {
    return this.$store.state.BASE_URL;  
  }

However, when I try to access the store in the methods of the same component:

  methods: {

    register: function () {
          axios.post( this.BASE_URL + "/web/register", {
          username: this.username,
          password: this.password,
          email: this.email
        }).then(function(data){
          this.$store.commit('saveToken', data.token);
          console.log('token is set to:',  this.$store.state.token)
        });
    }  
 },

I get this error at the console:

Uncaught (in promise) TypeError: Cannot read property '$store' of undefined

I have also tried $store without this but get the same error.

What is wrong here? How can I fix it?

like image 226
Karlom Avatar asked Sep 21 '17 04:09

Karlom


1 Answers

You're using a javascript function instead of an arrow function. Try this and it should work.

 methods: {
    register () {
          axios.post( this.BASE_URL + "/web/register", {
          username: this.username,
          password: this.password,
          email: this.email
        }).then( (data) => {
          this.$store.commit('saveToken', data.token);
          console.log('token is set to:',  this.$store.state.token)
        });
    }  
like image 153
Jerico Pulvera Avatar answered Sep 25 '22 21:09

Jerico Pulvera