Reputation: 159
I'm using vue webpack template with vuex and I'm basically having issues with components not updating with the state.
I have a store
const state = {
userData: {},
}
In my app I have a method
methods: {
addUserData: function() {
const that = this;
axios.get('URL').then(function (response) {
let obj = response.data;
that.$store.commit('addUserData', {obj});
});
},
which I call when it's mounted
mounted () {
this.addUserData();
},
Which is updated with a mutation
const mutations = {
addUserData(state, {obj}) {
state.userData = obj;
},}
Everything is fine up to here, the data is going into the store fine. But then I have a component which isn't working, as it's not waiting for the ajax to finish loading, nor is it binded in any way. I may well be doing this wrong here, but basically in my component I have
data () {
return {
weekData : {
weekDataList: []....
methods: {
tester: function(a) {
// Sorting the userdata using lowdash
this.weekData.weekDataList = _.values(this.$store.state.userData);
},
},
I call this in the same manner as I did before
mounted () {
this.tester();
},
The issue is that this.weekData.weekDataList always returns an empty array as the userData in the store hasn't managed to complete. I have dozens of methods performing various calculations, all based on this one array, so if one fails they all fail.
Perhaps my approach is wrong, but ideally I would like the data attributes to update once the store is updated? I tried doing this with computed properties and works fine with {{ whatever }}, but wasn't sure how to update the components data.
Upvotes: 3
Views: 1696
Reputation: 198
you were on the right paths. Computed properties is definitely the way to go here. In you current situation your component knows nothing about the store in any reactive way. You just have a function that tries to read out the data at any given point and the correct data may be there or not.
So first of all, if the component is nested under the parent, as it seems to be this.$store
will point to the same store. You should then try to use the needed value as a property, so it's reactive.
computed: {
userData: function () {
return this.$store.state.userData
}
}
and while you are on it, also throw the weekdata into the computed properties:
computed: {
userData: function () {
return this.$store.state.userData
},
weekData: function () {
return {
weekDataList: _.values(this.userData)
}
}
}
By doing this, all the data will be reactive, and the weekData
will update accordingly.
Hope this helps, and in general, when you are using Webpack already, I would consider starting to use the ES6 Syntax as it makes things more readable and some parts a little cleaner :)
Upvotes: 1