Vuex存储在组件库中

时间:2020-08-12 07:22:06

标签: typescript vue.js vuejs2 vuex

我正在构建组件库,并且我的某些组件需要了解Vuex商店。让我们以我的组件库中的Textbox组件为例。装入组件后,我可以看到已填充“ this。$ store”。但是,当我在主应用程序中对商店进行更新时,所做的更改不会反映在组件库的“文本框”组件中。我正在使用“ 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
};

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

0 个答案:

没有答案