官方文檔git
vuex 使用單一狀態樹——是的,用一個對象就包含了所有的應用層級狀態。github
// 建立一個 Counter 組件,在computed中返回。 const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { //vuex的狀態存儲是響應式的 return store.state.count } } }
咱們可使用 mapState 輔助函數幫助咱們生成計算屬性,將組件中的computed屬性映射爲 store 中的 statevuex
// 在單獨構建的版本中輔助函數爲 Vuex.mapState import { mapState } from 'vuex' export default { // ... computed: mapState({ // 箭頭函數可以使代碼更簡練 count: state => state.count, // 傳字符串參數 'count' 等同於 `state => state.count` countAlias: 'count', // 爲了可以使用 `this` 獲取局部狀態,必須使用常規函數 countPlusLocalState (state) { return state.count + this.localCount } }) }
當映射的計算屬性的名稱與 state 的子節點名稱相同時,咱們也能夠給 mapState 傳一個字符串數組。數組
computed: mapState([ // 映射 this.count 爲 store.state.count 'count' ])
Vuex 容許咱們在 store 中定義「getter」(能夠認爲是 store 的計算屬性)。就像計算屬性同樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被從新計算。緩存
Getter 接受 state 做爲其第一個參數:babel
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
Getter 會暴露爲 store.getters 對象:app
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter 也能夠接受其餘 getter 做爲第二個參數:異步
getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length } } store.getters.doneTodosCount // -> 1
咱們能夠很容易地在任何組件中使用它:ide
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
你也能夠經過讓 getter 返回一個函數,來實現給 getter 傳參。在你對 store 裏的數組進行查詢時很是有用。
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } } store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
咱們可使用 mapGetter 輔助函數幫助咱們生成計算屬性,將組件中的computed屬性映射爲 store 中的 getter
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用對象展開運算符將 getter 混入 computed 對象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
若是你想將一個 getter 屬性另取一個名字,使用對象形式:
mapGetters({ // 映射 `this.doneCount` 爲 `store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
更改 Vuex 的 store 中的狀態的惟一方法是提交 mutation。Vuex 中的 mutation 很是相似於事件:每一個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是咱們實際進行狀態更改的地方,而且它會接受 state 做爲第一個參數:
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 變動狀態 state.count++ } } })
當觸發一個類型爲 increment 的 mutation 時,調用此函數。」要喚醒一個 mutation handler,你須要以相應的 type 調用 store.commit 方法:
store.commit('increment')
1.傳入額外的參數,即 mutation 的 載荷(payload):
// ... mutations: { increment (state, n) { state.count += n } } store.commit('increment', 10)
2.載荷是一個對象
// ... mutations: { increment (state, payload) { state.count += payload.amount } } store.commit('increment', { amount: 10 })
提交 mutation 的另外一種方式是直接使用包含 type 屬性的對象:
mutations: { increment (state, payload) { state.count += payload.amount } } store.commit({ type: 'increment', amount: 10 })
這樣可使 linter 之類的工具發揮做用,同時把這些常量放在單獨的文件中可讓你的代碼合做者對整個 app 包含的 mutation 一目瞭然:
// mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION' // store.js import Vuex from 'vuex' import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({ state: { ... }, mutations: { // 咱們可使用 ES2015 風格的計算屬性命名功能來使用一個常量做爲函數名 [SOME_MUTATION] (state) { // mutate state } } })
注意:一條重要的原則就是要記住 mutation 必須是同步函數。
你能夠在組件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 輔助函數將組件中的methods映射爲 store.commit 調用(須要在根節點注入 store)。
import { mapMutations } from 'vuex' export default { // ... methods: { ...mapMutations([ 'increment', // 將 `this.increment()` 映射爲 `this.$store.commit('increment')` // `mapMutations` 也支持載荷: 'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.commit('incrementBy', amount)` ]), ...mapMutations({ add: 'increment' // 將 `this.add()` 映射爲 `this.$store.commit('increment')` }) } }
Action 相似於 mutation,不一樣在於:
讓咱們來註冊一個簡單的 action:
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })
Action 函數接受一個與 store 實例具備相同方法和屬性的 context 對象,所以你能夠調用 context.commit 提交一個 mutation,或者經過 context.state 和 context.getters 來獲取 state 和 getters。
Action 經過 store.dispatch 方法觸發:
store.dispatch('increment')
顯然直接分發mutation更方便,可是mutation 必須同步執行,Action 則不受這個限制
咱們能夠在action內部執行異步操做
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
Actions 支持一樣的載荷方式和對象方式進行分發:
// 以載荷形式分發 store.dispatch('incrementAsync', { amount: 10 }) // 以對象形式分發 store.dispatch({ type: 'incrementAsync', amount: 10 })
你在組件中使用 this.$store.dispatch('xxx') 分發 action,或者使用 mapActions 輔助函數將組件的methods映射爲 store.dispatch 調用(須要先在根節點注入 store):
import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment', // 將 `this.increment()` 映射爲 `this.$store.dispatch('increment')` // `mapActions` 也支持載荷: 'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')` }) } }
因爲使用單一狀態樹,應用的全部狀態會集中到一個比較大的對象。當應用變得很是複雜時,store 對象就有可能變得至關臃腫。
爲了解決以上問題,Vuex 容許咱們將 store 分割成模塊(module)。每一個模塊擁有本身的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行一樣方式的分割:
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 的狀態
對於模塊內部的 mutation 和 getter,接收的第一個參數是模塊的局部狀態對象。
const moduleA = { state: { count: 0 }, mutations: { increment (state) { // 這裏的 `state` 對象是模塊的局部狀態 state.count++ } }, getters: { doubleCount (state) { return state.count * 2 } } }
一樣,對於模塊內部的 action,局部狀態經過 context.state 暴露出來,根節點狀態則爲 context.rootState:
const moduleA = { // ... actions: { incrementIfOddOnRootSum ({ state, commit, rootState }) { if ((state.count + rootState.count) % 2 === 1) { commit('increment') } } } }
對於模塊內部的 getter,根節點狀態會做爲第三個參數暴露出來:
const moduleA = { // ... getters: { sumWithRootCount (state, getters, rootState) { return state.count + rootState.count } } }
以menu爲了分析下思路
1.app.js
import 'babel-polyfill' import Vue from 'vue' import App from './components/App.vue' import store from './store' //步驟1 import { currency } from './currency' Vue.filter('currency', currency) new Vue({ el: '#app', store, //步驟2 render: h => h(App) })
作了兩步 : 引入store 並綁定到根實例上
2.store/index.js
import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as getters from './getters' import fruit from './modules/fruit'; Vue.use(Vuex) const store = new Vuex.Store({ actions, getters, modules: { fruit, }, }) export default store;
3.store/nutation-types.js
export const FRUIT_SHOW = "FRUIT_SHOW" export const FRUIT_HIDE = "FRUIT_HIDE"
4.store/modules/fruit.js
import {FRUIT_SHOW,FRUIT_HIDE,} from '../../store/mutation-types' export default { state: { appearence: false, }, mutations: { [FRUIT_HIDE](state) { state.appearence = false }, [FRUIT_SHOW](state) { state.appearence = true }, }, actions: { hideFruit({commit}) { commit(FRUIT_HIDE) }, showFruit({commit}) { commit(FRUIT_SHOW) }, }, getters: { fruitState:state => state.appearence, } }
5.使用方法
<template> <div> <p v-if="appearence">apple</p> <el-button type="primary" @click="showApple">顯示</el-button> <el-button @click="hideApple">隱藏</el-button> </div> </template>
<script> import { mapState } from 'vuex'; import { mapGetters } from 'vuex'; export default { data () { return { } }, methods: { showApple(){ //使用commit觸發mutations this.$store.commit('FRUIT_SHOW'); //使用dispatch觸發actions,action中使用commit觸發mutations //this.$store.dispatch('showFruit'); }, hideApple(){ //this.$store.commit('FRUIT_HIDE'); this.$store.dispatch('hideFruit'); }, }, //使用getters computed: mapGetters({ appearence: 'fruitState', }), /** //使用 state computed: mapState({ //appearence: appearence, 這樣是錯誤,少了一層fruit appearence: state => state.fruit.appearence, }), //另外一種表示方法 computed:{ ...mapState({ appearence: state => state.fruit.appearence, }) }, **/ mounted() { //使用state獲取狀態 console.log(this.$store.state.fruit.appearence); //使用getters獲取狀態 console.log(this.$store.getters.fruitState); }, } </script>
6.另外一種定義getters的方法
store/modules/fruit.js
import { FRUIT_SHOW, FRUIT_HIDE, } from '../../store/mutation-types' export default { state: { appearence: false, }, mutations: { [FRUIT_HIDE](state) { state.appearence = false }, [FRUIT_SHOW](state) { state.appearence = true }, }, actions: { hideFruit({commit}) { commit(FRUIT_HIDE) }, showFruit({commit}) { commit(FRUIT_SHOW) }, }, //這裏不在定義getters }
store/getters.js
const fruitState = (state) => state.fruit.appearence; export { fruitState, }