首页 > 解决方案 > Vuex 存储在组件库中

问题描述

我正在构建一个组件库,我的一些组件需要了解 Vuex 商店。让我们以我的组件库中的 Textbox 组件为例。当组件挂载时,我可以看到“this.$store”已填充。但是当我在主应用程序中对存储进行更新时,这些更改不会反映在组件库中的 Textbox 组件中。我正在使用“vue-property-decorator”在 Typescript 中编写组件。以下是一些关于如何将商店传递到库的代码片段

main.ts(组件库)

import * as components from './components'

const ComponentLibrary = {
  install(Vue, options) {
    if (!options || !options.store) {
      throw new Error('Please initialise plugin with a Vuex store.')
    }
    
    // components
    for (const componentName in components) {
      const component = components[componentName]
      Vue.component(component.name, component)
    }
  }
}

export default ComponentLibrary

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(ComponentLibrary)
}

main.ts(主项目)

import store from './store/store';
import ComponentLib from 'component-library/src/main';

Vue.use(ComponentLib, { store });

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');

store.ts(主项目)

import Vue from 'vue';
import Vuex from 'vuex';
import modules from './modules';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: modules,
});

模块包含每个单独的存储文件 /* Common.store.ts */

const state = {
    mode: [], //Default mode 
};

const mutations = {
    ADD_MODE(state, data) {
        let index = state.mode.findIndex(o => o.routeName == data.routeName);
        index !== -1 ? state.mode[index] = data : state.mode.push(data);
    },
};

const actions = {
  AddMode({ commit, state }, data) {
    commit('ADD_MODE', data);
  }
}

const getters = {
mode: (state) => {
    return state.mode;
  },
}

export default {
  namespaced: true,
  mutations,
  state,
  getters,
  actions
};

现在在 TextBox 组件中,当我尝试访问 this.$store.state.Common.mode 时,从 Vue Devtools 更新模式值不会更新组件库中的值。如果我在主应用程序中访问 this.$store.state.Common.mode,我可以实时看到变化。我错过了什么?提前感谢您的帮助。另外,如果需要更多信息,请告诉我。

标签: typescriptvue.jsvuejs2vuex

解决方案


推荐阅读