Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS: how to reference this.$store in component data property

I am wanting to use my Vuex store data in my app and template.

My Veux store:

var Vue = require('vue');
var Vuex = require('vuex');

Vue.use(Vuex)

let store = new Vuex.Store({
        state: {
            user: {},
        },
    }
}
module.exports = store

I want to use the store data in my app and display it in the template. But, when setting the data in the data property, this.$store is undefined. I am, however, able to access it in the beforeRender function:

var Vue = require('vue'),
store = require('../../link/to/my/store');

module.exports = {
    el: '#selector',

    store,

    components: {},

    data: {
        saving: false,
        user: this.$store.state.user // this.state is not available here
    },

    created: function(){},
    beforeCreate: function() {

        console.log(this.$state.state) // this.$state is available here

        // i get my data in the form of a json string from the dom
        // and update the global store with the data
        let user = document.querySelector('#user-data')
        if (user) this.$store.dispatch('updateUser', JSON.parse(user.innerHTML))

    },

    methods: {}

    }
};

I have also tried with a computed property but to no avail.

like image 509
johnm Avatar asked Apr 27 '17 15:04

johnm


People also ask

What is REF () in Vue?

Ref s are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.

How do you access props in data Vue?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.


1 Answers

As per the Vue documentation:

When defining a component, data must be declared as a function that returns the initial data object.

So, change:

data: {
    saving: false,
    user: this.$store.state.user
},

to this:

data: function () {
  return {
    saving: false,
    user: this.$store.state.user
  };
}

Then the this in the function will have a reference to $store.

like image 98
thanksd Avatar answered Oct 18 '22 20:10

thanksd