數(shù)據(jù)管理

2020-05-14 14:20 更新

利用這種數(shù)據(jù)管理模式在組件外部集中管理狀態(tài),可方便構(gòu)建一個中大型單頁應(yīng)用

chameleon-store 提供集中管理數(shù)據(jù)的能力。

這是一個簡單的例子:

項目結(jié)構(gòu)

Chameleon 內(nèi)置 store 并不限制你的代碼結(jié)構(gòu)。但是,它規(guī)定了一些需要遵守的規(guī)則:

  1. 應(yīng)用層級的狀態(tài)應(yīng)該集中到單個 store 對象中。
  2. 提交 mutation 是更改狀態(tài)的唯一方法,并且這個過程是同步的。
  3. 異步邏輯都應(yīng)該封裝到 action 里面。

只要你遵守以上規(guī)則,如何組織代碼隨你便。如果你的 store 文件太大,只需將 action、mutation 和 getter 分割到單獨的文件。

對于大型應(yīng)用,我們會希望把 CML 相關(guān)代碼分割到模塊中。下面是項目結(jié)構(gòu)示例:

├── app
├── assets
├── pages                 # 頁面
│   └── ...
├── components            # 組件
│   ├── c-todoitem
│   └── ...
└── store
    ├── action-types.js   # 定義 actions 的類型
    ├── actions.js        # 根級別的 actions
    ├── getter-types.js   # 定義 getters 的類型
    ├── getters.js        # 根級別的 getters
    ├── index.js          # 我們組裝模塊并導(dǎo)出 store 的地方
    ├── mutation-types.js # 定義 mutations 的類型
    ├── mutations.js      # 根級別的 mutation
    ├── state.js          # 組件初始狀態(tài)數(shù)據(jù)
    └── modules           # 子模塊
        ├── ...

開始

“store”基本上就是一個容器,它包含著你的應(yīng)用中大部分的狀態(tài) (state)。store 和單純的全局對象有以下兩點不同:

  1. store 的狀態(tài)存儲是響應(yīng)式的。當(dāng) CML 組件從 store 中讀取狀態(tài)的時候,若 store 中的狀態(tài)發(fā)生變化,那么相應(yīng)的組件也會相應(yīng)地得到高效更新。
  2. 你不能直接改變 store 中的狀態(tài)。改變 store 中的狀態(tài)的唯一途徑就是顯式地提交 (commit) mutation。

最簡單的 store

創(chuàng)建 store,并且提供一個初始 state 對象和一些 mutation:

import createStore from 'chameleon-store';

const store = createStore({
  state: {
    count: 0,
  },
  mutations: {
    increment(state) {
      state.count++;
    },
  },
});
export default store;

通過 store.state 來獲取狀態(tài)對象,以及通過 store.commit 方法觸發(fā)狀態(tài)變更:

store.commit('increment');

console.log(store.state.count); // -> 1

再次強(qiáng)調(diào),我們通過提交 mutation 的方式,而非直接改變 store.state.count,是因為我們想要更明確地追蹤到狀態(tài)的變化。這個簡單的約定能夠讓你的意圖更加明顯,這樣你在閱讀代碼的時候能更容易地解讀應(yīng)用內(nèi)部的狀態(tài)改變。此外,這樣也讓我們有機(jī)會去實現(xiàn)一些能記錄每次狀態(tài)改變,保存狀態(tài)快照的調(diào)試工具。有了它,我們甚至可以實現(xiàn)如時間穿梭般的調(diào)試體驗。

由于 store 中的狀態(tài)是響應(yīng)式的,在組件中調(diào)用 store 中的狀態(tài)簡單到僅需要在計算屬性中返回即可。觸發(fā)變化也僅僅是在組件的 methods 中提交 mutation。

接下來,我們將會更深入地探討一些核心概念。讓我們先從State概念開始。

類似 Vuex 數(shù)據(jù)理念和語法規(guī)范,chameleon-store 主要有以下核心概念:

State

單一狀態(tài)樹

chameleon-store 用一個對象就包含了全部的應(yīng)用層級狀態(tài)。單一狀態(tài)樹讓我們能夠直接地定位任一特定的狀態(tài)片段,在調(diào)試的過程中也能輕易地取得整個當(dāng)前應(yīng)用狀態(tài)的快照。

單狀態(tài)樹和模塊化并不沖突——在后面的章節(jié)里我們會討論如何將狀態(tài)和狀態(tài)變更事件分布到各個子模塊中。

在 CML 組件中獲得 store 狀態(tài)

那么我們?nèi)绾卧?CML 組件中展示狀態(tài)呢?由于 CML 內(nèi)置的 store 的狀態(tài)存儲是響應(yīng)式的,從 store 實例中讀取狀態(tài)最簡單的方法就是在計算屬性中返回某個狀態(tài):

import store from '../store';
// 創(chuàng)建一個 Counter 組件
const Counter = {
  computed: {
    count() {
      return store.state.count;
    },
  },
};

每當(dāng) store.state.count 變化的時候, 都會重新求取計算屬性,并且觸發(fā)更新相關(guān)聯(lián)的 DOM。

mapState輔助函數(shù)

當(dāng)一個組件需要獲取多個狀態(tài)時候,將這些狀態(tài)都聲明為計算屬性會有些重復(fù)和冗余。為了解決這個問題,我們可以使用 mapState 輔助函數(shù)幫助我們生成計算屬性,讓你少按幾次鍵:

// 在單獨構(gòu)建的版本中輔助函數(shù)為 CML 內(nèi)置的store.mapState
import store from '../store';

class Index {
  // ...
  computed = store.mapState({
    // 箭頭函數(shù)可使代碼更簡練
    count: (state) => state.count,

    // 傳字符串參數(shù) 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù)
    countPlusLocalState(state) {
      return state.count + this.localCount;
    },
  });
}
export default new Index();

當(dāng)映射的計算屬性的名稱與 state 的子節(jié)點名稱相同時,我們也可以給 mapState 傳一個字符串?dāng)?shù)組。

import store from '../store';

class Index {
  computed = store.mapState([
    // 映射 this.count 為 store.state.count
    'count',
  ]);
}
export default new Index();

對象展開運(yùn)算符

mapState 函數(shù)返回的是一個對象。我們?nèi)绾螌⑺c局部計算屬性混合使用呢?通常,我們需要使用一個工具函數(shù)將多個對象合并為一個,以使我們可以將最終對象傳給 computed 屬性。但是自從有了對象展開運(yùn)算符(現(xiàn)處于 ECMASCript 提案 stage-3 階段),我們可以極大地簡化寫法:

import store from '../store';

class Index {
  computed = {
    localComputed() {
      /* ... */
    },
    // 使用對象展開運(yùn)算符將此對象混入到外部對象中
    ...store.mapState({
      // ...
    }),
  };
}
export default new Index();

組件仍然保有局部狀態(tài)

使用 CML 內(nèi)置的 store 并不意味著你需要將所有的狀態(tài)放入store。雖然將所有的狀態(tài)放到 CML 內(nèi)置的 store 會使?fàn)顟B(tài)變化更顯式和易調(diào)試,但也會使代碼變得冗長和不直觀。如果有些狀態(tài)嚴(yán)格屬于單個組件,最好還是作為組件的局部狀態(tài)。你應(yīng)該根據(jù)你的應(yīng)用開發(fā)需要進(jìn)行權(quán)衡和確定。

Getter

有時候我們需要從 store 中的 state 中派生出一些狀態(tài),例如對列表進(jìn)行過濾并計數(shù):

computed: {
  doneTodosCount () {
    return store.state.todos.filter(todo => todo.done).length
  }
}

如果有多個組件需要用到此屬性,我們要么復(fù)制這個函數(shù),或者抽取到一個共享函數(shù)然后在多處導(dǎo)入它——無論哪種方式都不是很理想。

chameleon 內(nèi)置 store 允許我們在 store 中定義“getter”(可以認(rèn)為是 store 的計算屬性)。就像計算屬性一樣,getter 的返回值會根據(jù)它的依賴被緩存起來,且只有當(dāng)它的依賴值發(fā)生了改變才會被重新計算。

Getter 接受 state 作為其第一個參數(shù):

import createStore from 'chameleon-store';

const store = createStore({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false },
    ],
  },
  getters: {
    doneTodos: (state) => {
      return state.todos.filter((todo) => todo.done);
    },
  },
});

export default store;

Getter 會暴露為 store.getters 對象:

store.getters.doneTodos; // -> [{ id: 1, text: '...', done: true }]

Getter 也可以接受其他 getter 作為第二個參數(shù), rootState 作為第三個參數(shù):

getters: {
  // ...
  doneTodosCount: (state, getters, rootState) => {
    return getters.doneTodos.length;
  };
}
store.getters.doneTodosCount; // -> 1

我們可以很容易地在任何組件中使用它:

computed: {
  doneTodosCount () {
    return store.getters.doneTodosCount
  }
}

你也可以通過讓 getter 返回一個函數(shù),來實現(xiàn)給 getter 傳參。在你對 store 里的數(shù)組進(jìn)行查詢時非常有用。

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find((todo) => todo.id === id);
  };
}
store.getters.getTodoById(2); // -> { id: 2, text: '...', done: false }

mapGetters輔助函數(shù)

mapGetters 輔助函數(shù)僅僅是將 store 中的 getter 映射到局部計算屬性:

import store from '../store';

class Index {
  // ...
  computed = {
    // 使用對象展開運(yùn)算符將 getter 混入 computed 對象中
    ...store.mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ]),
  };
}
export default new Index();

如果你想將一個 getter 屬性另取一個名字,使用對象形式:

store.mapGetters({
  // 映射 `this.doneCount` 為 `store.getters.doneTodosCount`
  doneCount: 'doneTodosCount',
});

Mutation

更改 CML 內(nèi)置 store 的 store 中的狀態(tài)的唯一方法是提交 mutation。chameleon 內(nèi)置 store 中的 mutation 非常類似于事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調(diào)函數(shù) (handler)。這個回調(diào)函數(shù)就是我們實際進(jìn)行狀態(tài)更改的地方,并且它會接受 state 作為第一個參數(shù):

import createStore from 'chameleon-store';

const store = createStore({
  state: {
    count: 1,
  },
  mutations: {
    increment(state) {
      // 變更狀態(tài)
      state.count++;
    },
  },
});

export default store;

你不能直接調(diào)用一個 mutation handler。這個選項更像是事件注冊:“當(dāng)觸發(fā)一個類型為 increment 的 mutation 時,調(diào)用此函數(shù)?!币獑拘岩粋€ mutation handler,你需要以相應(yīng)的 type 調(diào)用 store.commit 方法:

store.commit('increment');

提交載荷(Payload)

你可以向 store.commit 傳入額外的參數(shù),即 mutation 的 載荷(payload):

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10);

在大多數(shù)情況下,載荷應(yīng)該是一個對象,這樣可以包含多個字段并且記錄的 mutation 會更易讀:

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10,
});

Mutation 需遵守 CML 的響應(yīng)規(guī)則

既然 CML 內(nèi)置 store 中的狀態(tài)是響應(yīng)式的,那么當(dāng)我們變更狀態(tài)時,監(jiān)視狀態(tài)的 CML 組件也會自動更新。這也意味著 CML 內(nèi)置 store 中的 mutation 也需要與使用 CML 一樣遵守一些注意事項:

  1. 最好提前在你的 store 中初始化好所有所需屬性。
  2. 當(dāng)需要在對象上添加新屬性時,你應(yīng)該
  • 以新對象替換老對象。例如,利用 stage-3 的對象展開運(yùn)算符我們可以這樣寫:state.obj = { ...state.obj, newProp: 123 };

使用常量替代 Mutation 事件類型

使用常量替代 mutation 事件類型在各種 Flux 實現(xiàn)中是很常見的模式。這樣可以使 linter 之類的工具發(fā)揮作用,同時把這些常量放在單獨的文件中可以讓你的代碼合作者對整個 app 包含的 mutation 一目了然:

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION';
// store.js
import createStore from 'chameleon-store'
import { SOME_MUTATION } from './mutation-types'

const store = createStore({
  state: { ... },
  mutations: {
    // 我們可以使用 ES2015 風(fēng)格的計算屬性命名功能來使用一個常量作為函數(shù)名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})
export default store

用不用常量取決于你——在需要多人協(xié)作的大型項目中,這會很有幫助。但如果你不喜歡,你完全可以不這樣做。

Mutation 必須是同步函數(shù)

一條重要的原則就是要記住 mutation 必須是同步函數(shù)。為什么?請參考下面的例子:

mutations: {
  someMutation (state) {
    api.callAsyncMethod(() => {
      state.count++
    })
  }
}

現(xiàn)在想象,我們正在 debug 一個 app 并且觀察 devtool 中的 mutation 日志。每一條 mutation 被記錄,devtools 都需要捕捉到前一狀態(tài)和后一狀態(tài)的快照。然而,在上面的例子中 mutation 中的異步函數(shù)中的回調(diào)讓這不可能完成:因為當(dāng) mutation 觸發(fā)的時候,回調(diào)函數(shù)還沒有被調(diào)用,devtools 不知道什么時候回調(diào)函數(shù)實際上被調(diào)用——實質(zhì)上任何在回調(diào)函數(shù)中進(jìn)行的狀態(tài)的改變都是不可追蹤的。

在組件中提交 Mutation

你可以在組件中使用 store.commit('xxx') 提交 mutation,或者使用 mapMutations 輔助函數(shù)將組件中的 methods 映射為 store.commit 調(diào)用。

import store from '../store';

createComponent({
  // ...
  methods: {
    ...store.mapMutations([
      'increment', // 將 `this.increment()` 映射為 `store.commit('increment')`

      // `mapMutations` 也支持載荷:
      'incrementBy', // 將 `this.incrementBy(amount)` 映射為 `store.commit('incrementBy', amount)`
    ]),
    ...store.mapMutations({
      add: 'increment', // 將 `this.add()` 映射為 `store.commit('increment')`
    }),
  },
});

下一步:Action

在 mutation 中混合異步調(diào)用會導(dǎo)致你的程序很難調(diào)試。例如,當(dāng)你調(diào)用了兩個包含異步回調(diào)的 mutation 來改變狀態(tài),你怎么知道什么時候回調(diào)和哪個先回調(diào)呢?這就是為什么我們要區(qū)分這兩個概念。在 CML 內(nèi)置 store 中,mutation 都是同步事務(wù):

store.commit('increment');
// 任何由 "increment" 導(dǎo)致的狀態(tài)變更都應(yīng)該在此刻完成。

Action

Action 類似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接變更狀態(tài)。
  • Action 可以包含任意異步操作。

讓我們來注冊一個簡單的 action:

import createStore from 'chameleon-store';
const store = createStore({
  state: {
    count: 0,
  },
  mutations: {
    increment(state) {
      state.count++;
    },
  },
  actions: {
    increment(context) {
      context.commit('increment');
    },
    increment2({ rootState, state, getters, dispatch, commit }) {},
  },
});
export default store;

Action 函數(shù)接受一個 context 對象,因此你可以調(diào)用 context.commit 提交一個 mutation,或者通過 context.rootState、context.state 和 context.getters 來獲取全局 state、局部 state 和 全局 getters。

實踐中,我們會經(jīng)常用到 ES2015 的參數(shù)解構(gòu)來簡化代碼(特別是我們需要調(diào)用 commit 很多次的時候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

分發(fā) Action

Action 通過 store.dispatch 方法觸發(fā):

store.dispatch('increment');

乍一眼看上去感覺多此一舉,我們直接分發(fā) mutation 豈不更方便?實際上并非如此,還記得 mutation 必須同步執(zhí)行這個限制么?Action 就不受約束!我們可以在 action 內(nèi)部執(zhí)行異步操作:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

Actions 支持同樣的載荷方式進(jìn)行分發(fā):

// 以載荷形式分發(fā)
store.dispatch('incrementAsync', {
  amount: 10,
});

來看一個更加實際的購物車示例,涉及到調(diào)用異步 API 和分發(fā)多重 mutation:

actions: {
  checkout ({ commit, state }, products) {
    // 把當(dāng)前購物車的物品備份起來
    const savedCartItems = [...state.cart.added]
    // 發(fā)出結(jié)賬請求,然后樂觀地清空購物車
    commit(types.CHECKOUT_REQUEST)
    // 購物 API 接受一個成功回調(diào)和一個失敗回調(diào)
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失敗操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

注意我們正在進(jìn)行一系列的異步操作,并且通過提交 mutation 來記錄 action 產(chǎn)生的副作用(即狀態(tài)變更)。

在組件中分發(fā) Action

你在組件中使用 store.dispatch('xxx') 分發(fā) action,或者使用 mapActions 輔助函數(shù)將組件的 methods 映射為 store.dispatch 調(diào)用:

import store from '../store';

class Index {
  methods = {
    ...store.mapActions([
      'increment', // 將 `this.increment()` 映射為 `store.dispatch('increment')`

      // `mapActions` 也支持載荷:
      'incrementBy', // 將 `this.incrementBy(amount)` 映射為 `store.dispatch('incrementBy', amount)`
    ]),
    ...store.mapActions({
      add: 'increment', // 將 `this.add()` 映射為 `store.dispatch('increment')`
    }),
  };
}
export default new Index();

組合 Action

Action 通常是異步的,那么如何知道 action 什么時候結(jié)束呢?更重要的是,我們?nèi)绾尾拍芙M合多個 action,以處理更加復(fù)雜的異步流程?

首先,你需要明白 store.dispatch 可以處理被觸發(fā)的 action 的處理函數(shù)返回的 Promise,并且 store.dispatch 仍舊返回 Promise:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

現(xiàn)在你可以:

store.dispatch('actionA').then(() => {
  // ...
});

在另外一個 action 中也可以:

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

最后,如果我們利用async / await,我們可以如下組合 action:

// 假設(shè) getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}
一個 store.dispatch 在不同模塊中可以觸發(fā)多個 action 函數(shù)。在這種情況下,只有當(dāng)所有觸發(fā)函數(shù)完成后,返回的 Promise 才會執(zhí)行。

Module

當(dāng)應(yīng)用變得非常復(fù)雜時,store 對象就有可能變得相當(dāng)臃腫。

為了解決以上問題,chameleon 內(nèi)置 store 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進(jìn)行同樣方式的分割:

import createStore from 'chameleon-store'
const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的狀態(tài)
store.state.b // -> moduleB 的狀態(tài)

模塊的局部狀態(tài)

對于模塊內(nèi)部的 mutation 和 getter,接收的第一個參數(shù)是模塊的局部狀態(tài)對象。

const moduleA = {
  state: { count: 0 },
  mutations: {
    increment(state) {
      // 這里的 `state` 對象是模塊的局部狀態(tài)
      state.count++;
    },
  },

  getters: {
    doubleCount(state) {
      return state.count * 2;
    },
  },
};

同樣,對于模塊內(nèi)部的 action,局部狀態(tài)通過 context.state 暴露出來,根節(jié)點狀態(tài)則為 context.rootState:

const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment');
      }
    },
  },
};

對于模塊內(nèi)部的 getter,根節(jié)點狀態(tài)會作為第三個參數(shù)暴露出來:

const moduleA = {
  // ...
  getters: {
    sumWithRootCount(state, getters, rootState) {
      return state.count + rootState.count;
    },
  },
};

模塊動態(tài)注冊

在 store 創(chuàng)建之后,你可以使用 store.registerModule 方法注冊模塊:

// 注冊模塊 `myModule`
store.registerModule('myModule', {
  // ...
});

之后就可以通過 store.state.myModule 訪問模塊的狀態(tài)。

API

ChameleonStore.createStore(options: Object): Object

Store 構(gòu)造器。

通過 chameleon-store 創(chuàng)建的 Store 實例,有以下方法:

Store.commit(type: string, payload?: any)

提交 mutation。

Store.dispatch(type: string, payload?: any)

分發(fā) action。

Store.mapState(map:Array<string>|Object<string>): Object

為組件創(chuàng)建計算屬性以返回 store 中的狀態(tài)。

Store.mapGetters(map:Array<string>|Object<string>): Object

為組件創(chuàng)建計算屬性以返回 getter 的返回值。

Store.mapMutations(map:Array<string>|Object<string>): Object

創(chuàng)建組件方法提交 mutation。

Store.mapActions(map:Array<string>|Object<string>): Object

創(chuàng)建組件方法分發(fā) action。

Store.registerModule(path: String, module: Module)

注冊一個動態(tài)模塊。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號