vuex store doesn't update component

Martin Kure picture Martin Kure · Feb 12, 2017 · Viewed 15.4k times · Source

I'm new to vue, so I'm probably making a rookie error.

I have a root vue element - raptor.js:

const Component = {
el: '#app',
store,
data: {
    productList: store.state.productlist
},
beforeCreate: function () {
    return store.dispatch('getProductList', 'getTrendingBrands');
},
updated: function (){
    console.log(111);
    startSlider();
}
};
const vm = new Vue(Component);

Using this template

<div class="grid-module-single popular-products" id="app">
<div class="row">
    <div class="popular-items-slick col-xs-12">
        <div v-for="product in productList">
            ...
        </div>
    </div>
</div>

My store is very simple store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';
import model from '../../utilities/model';

Vue.use(Vuex);

export default new Vuex.Store({
state: {
    productlist: []
},
mutations: {
    setProductList(state, data) {
        state.productlist = data;
    }
},
actions: {
    getProductList({ commit }, action) {
        return model.products().then(data => commit('setProductList', data));
    }
}
});

In my vuex devtool, I can see, that the store is being updated https://www.screencast.com/t/UGbw7JyHS3

but my component is not being updated: https://www.screencast.com/t/KhXQrePEd

Question:

I can see from the devtools, that my code is working. The store is being updated with data. My component is not being updated,however. I thought it was enough just to add this in the data property on the component:

data: {
    productList: store.state.productlist
}

but apparently the data object doesn't seem to be automatically synced with the store. So either I'm doing a complete vue no-no somewhere, or I need to tweak the code a bit. Anyway can anyone help me in the right direction.

Thanks a lot.

Answer

Martin Kure picture Martin Kure · Feb 12, 2017

UPDATE

Figured it out myself. Just had to replace the components data part with a computed method:

data:

data: {
  productList: store.state.productlist
}

and replace it with.

computed: {
    productList () {
        return store.state.productlist;
    }
},