Vuex 是一个易于使用和高性能的解决方案来处理状态管理,它使它成为管理大规模 Vue.js 应用程序的乐趣,并通过暴露一个商店来确保一种可预测的方式来改变状态。
你可能已经知道Vuex,但如果你没有,Joshua Bemenderfer给了我们一个 伟大的介绍。
您可以在 Vuex 商店中定义模块如下:
1const dogs = {
2 state: {
3 data: []
4 },
5 mutations: {
6 addDog(state, dog) {
7 state.data.push(dog)
8 }
9 }
10}
11
12const store = new Vuex.Store({
13 modules: {
14 dogs
15 }
16});
通常,一个大型应用程序有几个模块. 它们都被定义为静态在自己的文件中,并在调用新Vuex.Store
时结合在一起。
但是,可能有一个非常具体的案例,你想动态地将Vuex模块加载到你的应用程序中,在那个时候扩展当前的商店。
一个非常具体的案例,比如你说什么?可以写一个依赖Vuex的外部组件库。
同样的情况也适用于分为多个内部包的应用程序,每个包都有自己的组件和仓库。
例如,提供某些通知组件的通知模块和扩展应用商店的商店模块,添加一个新模块,可在应用程序中的任何地方访问。
让我们看看如何做到这一点。
动态地将模块添加到商店
考虑到具有常规Vuex设置的应用程序,让我们创建一个通知文件夹. 您可以将其放置在您想要的任何地方,只要想象它是一个外部包。
在那里,添加一个 state.js 和一个基本的 Vuex 模块:
1[label notifications/state.js]
2export default {
3 state: [],
4 mutations: {
5 addNotification(state, notification) {
6 state.push(notification);
7 }
8 }
9};
然后创建一个 Notifications.vue 文件,导入它,然后访问$store
实例变量,假设有 Vuex 商店来获取状态并执行addNotification
:
1[label notifications/Notifications.vue]
2<template>
3 <div>
4 <p v-for="notification in notifications">
5 {{notification}}
6 </p>
7 <button @click="addHey">Add Hey!</button>
8 </div>
9</template>
10
11<script>
12import state from "./state";
13
14export default {
15 computed: {
16 notifications() {
17 return this.$store.state.notifications;
18 }
19 },
20 methods: {
21 addHey() {
22 this.$store.commit("addNotification", "Hey!");
23 }
24 }
25};
26</script>
现在,想法是Vuex模块在使用组件时会添加自己,因此,如果外部应用程序正在使用该组件,它已经被包装了,并且应用程序不必直接添加它。
并且,为了动态地添加Vuex模块,我们可以使用商店的实例属性$store.registerModule
:
1[label notifications/Notifications.vue]
2import state from "./state";
3
4export default {
5 // ...
6 created() {
7 this.$store.registerModule("notifications", state);
8 }
9};
现在,当使用通知组件时,该模块将被注册。
包装上
大型应用程序中的Vuex商店是通过不同的模块静态组织的,这就是它应该是这样的方式,但在非常具体的情况下,你可能需要扩展商店并自己添加一个模块。
您可以看到本文的工作演示文稿和代码在 This Codesandbox
保持冷静