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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.