vuex store 不更新组件

vuex store doesn't update component

我是 vue 新手,所以我可能犯了一个新手错误。

我有一个根 vue 元素 - 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);

使用此模板

<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>

我的店铺很简单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));
    }
}
});

在我的 vuex devtool 中,我可以看到商店正在更新 https://www.screencast.com/t/UGbw7JyHS3

但我的组件没有更新: https://www.screencast.com/t/KhXQrePEd

问题:

我可以从开发工具中看到,我的代码正在运行。商店正在更新数据。但是,我的组件没有更新。我认为只需将其添加到组件的数据 属性 中就足够了:

data: {
    productList: store.state.productlist
}

但显然数据对象似乎没有自动与商店同步。所以要么我在某个地方做一个完整的 vue 禁忌,要么我需要稍微调整一下代码。无论如何,任何人都可以在正确的方向上帮助我。

非常感谢。

更新

我自己想出来了。只需用计算方法替换组件数据部分:

数据:

data: {
  productList: store.state.productlist
}

并将其替换为。

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

data 在渲染之前只在组件上工作一次,所以你可以使用 computed 代替。 像上面的答案,或者你可以使用 mapstate

import {mapState} from 'vuex'
...
computed: mapState({
  productList: state => state.productList
})             

首先 - 使用 getter 执行此操作 mapGetters,您还需要以某种方式观看此 属性,您可以设置商店订阅或仅使用 watch 方法通过组件。

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

您以错误的方式将商店调用到 productList 数据中 属性。

你可以试试:

data: {
  productList: $store.state.productlist
}

否则您必须在每个使用商店的组件中导入商店。