Vuex 是用來(lái)處理狀態(tài)管理的高性能解決方案。它使管理大型 Vue.js 變得更輕松,并通過(guò)暴露出來(lái)的 store 使得狀態(tài)變得可預(yù)測(cè)。
你可能已經(jīng)知道 Vuex,如果不是的話 Joshua Bemenderfer 在下面為我們很好的 介紹它。
你可以像下面這樣定義 Vuex store 模塊:
const dogs = { state: { data: [] }, mutations: { addDog(state, dog) { state.data.push(dog) } } } const store = new Vuex.Store({ modules: { dogs } });
通常一個(gè)大型應(yīng)用都會(huì)有很多個(gè)模塊,所有模塊都定義在自己的文件中,并通過(guò)調(diào)用 new Vuex.Store
時(shí)結(jié)合在一起。這也是你一般的處理方法。
但可能會(huì)有一個(gè)特殊情況,你需要將 Vuex 模塊動(dòng)態(tài)地加載到你的應(yīng)用程序中,從而擴(kuò)展到當(dāng)前的 store 中。
一個(gè)比較具體的例子就是編寫一個(gè)依賴于 Vuex 的外部組件庫(kù)。
這同樣適用于分為幾個(gè)內(nèi)部軟件包的應(yīng)用程序。每個(gè)包,可能有自己的組件 和儲(chǔ)存。
通常,在應(yīng)用程序中這是常見的可重用的模塊。例如, 一個(gè) notifications
模塊提供一些通知組件以及一個(gè) store
模塊擴(kuò)展你的應(yīng)用程序存儲(chǔ), 這樣在你的應(yīng)用程序中添加一個(gè)新的模塊在任何一個(gè)地方都可以訪問(wèn)。
讓我們一起來(lái)看看它是怎樣實(shí)現(xiàn)的吧。
動(dòng)態(tài)為存儲(chǔ)新增模塊
因?yàn)槲覀兪褂昧?Vuex 的一般設(shè)置,接下來(lái)我們創(chuàng)建一個(gè) notifications
文件夾,你可以放在任意位置,想象他是一個(gè)外設(shè)的擴(kuò)展。
在此文件夾下新建 state.js
文件作為我們的 Vuex 模塊:
export default { state: [], mutations: { addNotification(state, notification) { state.push(notification); } } };
然后創(chuàng)建一個(gè) Notifications.vue
文件并導(dǎo)入。然后您將訪問(wèn) $store
實(shí)例變量,假設(shè)有一個(gè) Vuex 存儲(chǔ)來(lái)獲取來(lái)獲取狀態(tài),并提交一個(gè)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>
現(xiàn)在,我們的想法是,當(dāng)使用組件時(shí), Vuex 模塊會(huì)自動(dòng)添加通知。這樣,如果外部應(yīng)用程序使用組件,它將會(huì)被打包進(jìn)來(lái),而應(yīng)用程序無(wú)需關(guān)心直接添加它,所以我們可以使用 created
鉤子。
并且,為了動(dòng)態(tài)添加 Vuex 模塊, 我們可以使用 store’s 的實(shí)例屬性 $store.registerModule
:
import state from "./state"; export default { // ... created() { this.$store.registerModule("notifications", state); } };
現(xiàn)在,當(dāng)使用 Notifications
組件時(shí),模塊將被自動(dòng)注冊(cè)。
包起來(lái)
大型應(yīng)用程序中的 Vuex 存儲(chǔ)是通過(guò)不同模塊靜態(tài)組織的。應(yīng)該是這樣的。但是在非常特殊的情況下,您可能需要擴(kuò)展存儲(chǔ)并自己添加一個(gè)模塊。
推薦教程:《JS教程》