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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With