Vuex store does not update component

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

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 a 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 see that the store is being updated https://www.screencast.com/t/UGbw7JyHS3

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

Question:

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

 data: { productList: store.state.productlist } 

but apparently the data object does not seem to sync automatically with the repository. So either I'm doing a full vue no-no, or I need to tweak the code a bit. Anyway, someone can help me in the right direction.

Thank you very much.

+5
source share
3 answers

UPDATE

I thought for myself. Just had to replace the component part of the components with a computed method:

:

 data: { productList: store.state.productlist } 

and replace it.

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

data only works once on a component before rendering, so you can use the calculation instead. as above or you can use mapstate

 import {mapstate} from 'vuex' ... computed: mapstate({ productList: state => state.productList }) 
+1
source

First use getter to do this mapGetters , you also need to look at this property somehow, you can set up a subscription to the store or simply using the crow method component.

  this.$store.subscribe((mutation, state) => { if (mutation.type === 'UPDATE_DATA') { ... } } 
+1
source

Source: https://habr.com/ru/post/1264136/


All Articles