Vue 动态加载 Vuex
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的具体内容,更多请关注百分百源码网其它相关文章!