12

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?

B. Desai
  • 16,414
  • 5
  • 26
  • 47
Karlom
  • 13,323
  • 27
  • 72
  • 116

1 Answers1

33

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)
        });
    }  
Jerico Pulvera
  • 1,032
  • 7
  • 15
  • Fantastic. This solved the issue. But why I can not use vanilla JS in the promise? – Karlom Sep 21 '17 at 05:04
  • 9
    function have their own 'this' instance so when you call this you get the instance of the function your inside in and not the vue instance. The typical solution to this in vanilla javascript is to create a temporary variable outside the function then use it inside the function. e.g var self = this; register: function () { self.$store.commit(); } – Jerico Pulvera Sep 21 '17 at 05:07
  • 2
    FYI, arrow functions are also *"vanilla"* JavaScript. – Phil Sep 21 '17 at 05:13
  • @Phil thanks for the information didn't know that the tutorial I learned it from is wrong about that. – Jerico Pulvera Sep 21 '17 at 05:17