vuex與super-vuex
super-vuex是一套用于簡化Vuex的數據架構。
適用場景
在繁重的中后臺項目中,引入vuex的作用如下:
super-vuex在這三種需求下都是和原生vuex的功能相同,在vuex原有功能上將mutation和action的定義和傳導機制改良為函數的寫法,在簡易數組改動邏輯的使用上提供push、pop、shift、unshift、splice的方法,可以在與、組件中自動地完成mutation,以及數據引用的路徑化,你可以通過load.allow去取到load模塊下的allow屬性。
使用體驗
下面通過簡單的demo比較下原生vuex和super-vuex使用細節上的不同。
一、狀態模塊化
由于使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常復雜時,store 對象就有可能變得相當臃腫。
Vuex:
const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... }}const moduleB = { state: { ... }, mutations: { ... }, actions: { ... }}const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB }})store.state.a // -> moduleA 的狀態store.state.b // -> moduleB 的狀態super-vue
自動將mutation邏輯執行,因此異步邏輯寫在commit中即可,相比之下節省了代碼量
import { ChildVuex } from "super-vuex";const child = new ChildVuex('...');child.value = { ... };child.setCommit = {...};const Main = new SuperVuex();Main.setModule(child);export default Main.init();路徑式獲取子模塊數據
數據路徑,在之后的所有方法中,數據路徑至關重要,它是一個數據的直觀路徑字符串,也就是上面[ChildVuex].value 數據定義的數據路徑。
'load.allow'
可以取到load模塊的allow屬性
二、操作方法
super-vuex的操作方法上告別了以往同步數組操作的繁雜過程,比如在以往的vuex模式中實現一個對數組的操作是效率偏低的,先在mutation中定義方法操作,后在action中commit或是在組件中commit,super-vuex很好的解決了這個問題,提供了一系列基礎的數組操作方法讓你操作數組非常簡單。
Vuex:
// 提交一個commitstore.commit({ type: 'increment', amount: 10})mutations: { // push increment (state, n) { state.arr = = [...state.arr, n] } // pop popArr(state) { state.arr = arr.pop() } // shift shiftArr(state) { state.arr.shift() } // unshift unshift(state) { state.arr.unshift('students', { name: 'huaping1', age: 302 }) } // deleteStudent deleteStudent(state) { state.arr.splice('students', 0, 1); },}...
新聞熱點
疑難解答
圖片精選