typescript - 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,我可以实时看到变化。我错过了什么?提前感谢您的帮助。另外,如果需要更多信息,请告诉我。
解决方案
推荐阅读
- puppet - puppet 模块代码中 puppet hiera() 和 lookup() 的区别
- rxjs - RxJS - 连接并合并两个可观察对象
- function - Rust 中的函数原型是什么?
- c# - 正则表达式至少需要 6 位数字,但数字可以在任何地方
- javascript - 如何使用 JavaScript 中的 JSON 数组中的数据为 chartJS 图形创建自定义工具提示?
- javascript - Parsley.js 中关于 data-parsley-`constraint`-message 的说明
- javascript - 嵌套的 .unionWith,每个级别有一个唯一的合并
- java - Hibernate 需要很长时间才能得到查询结果
- php - 即使使用 catch,Php-fpm 仍然会记录我的错误
- python - 从图像上字符的坐标(横坐标和纵坐标)重建文本