
Vuex 是用来处理状态管理的高性能解决方案。它使管理大型 Vue.js 变得更轻松,并通过暴露出来的 store 使得状态变得可预测。
你可能已经知道 vuex,如果不是的话 joshua bemenderfer 在下面为我们很好的 介绍它。
你可以像下面这样定义 Vuex store 模块:
const dogs = {
state: {
data: []
},
mutations: {
addDog(state, dog) {
state.data.push(dog)
}
}
}
const store = new Vuex.Store({
modules: {
dogs
}
});通常一个大型应用都会有很多个模块,所有模块都定义在自己的文件中,并通过调用 new Vuex.Store 时结合在一起。这也是你一般的处理方法。
但可能会有一个特殊情况,你需要将 Vuex 模块动态地加载到你的应用程序中,从而扩展到当前的 store 中。
一个比较具体的例子就是编写一个依赖于 Vuex 的外部组件库。
立即学习“前端免费学习笔记(深入)”;
这同样适用于分为几个内部软件包的应用程序。每个包,可能有自己的组件 和储存。
通常,在应用程序中这是常见的可重用的模块。例如, 一个 notifications 模块提供一些通知组件以及一个 store 模块扩展你的应用程序存储, 这样在你的应用程序中添加一个新的模块在任何一个地方都可以访问。
让我们一起来看看它是怎样实现的吧。
因为我们使用了 Vuex 的一般设置,接下来我们创建一个 notifications 文件夹,你可以放在任意位置,想象他是一个外设的扩展。
在此文件夹下新建 state.js 文件作为我们的 Vuex 模块:
export default {
state: [],
mutations: {
addNotification(state, notification) {
state.push(notification);
}
}
};然后创建一个 Notifications.vue 文件并导入。然后您将访问 $store 实例变量,假设有一个 Vuex 存储来获取来获取状态,并提交一个addNotification:
<template>
<p>
<p v-for="notification in notifications">
{{notification}}
</p>
<button @click="addHey">Add Hey!</button>
</p>
</template>
<script>
import state from "./state";
export default {
computed: {
notifications() {
return this.$store.state.notifications;
}
},
methods: {
addHey() {
this.$store.commit("addNotification", "Hey!");
}
}
};
</script>现在,我们的想法是,当使用组件时, Vuex 模块会自动添加通知。这样,如果外部应用程序使用组件,它将会被打包进来,而应用程序无需关心直接添加它,所以我们可以使用 created 钩子。
并且,为了动态添加 Vuex 模块, 我们可以使用 store’s 的实例属性 $store.registerModule:
import state from "./state";
export default {
// ...
created() {
this.$store.registerModule("notifications", state);
}
};现在,当使用 Notifications 组件时,模块将被自动注册。
大型应用程序中的 Vuex 存储是通过不同模块静态组织的。应该是这样的。但是在非常特殊的情况下,您可能需要扩展存储并自己添加一个模块。
推荐教程:《JS教程》
以上就是Vue 动态加载 Vuex的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号