vue 狀態(tài)管理vuex

在viwe同級(jí)別建立store 文件
因?yàn)閟rore把 一些功能可以分模塊管理,在store中分布定義統(tǒng)一注入;

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

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

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
store.state.a.xxx // -> moduleA 的狀態(tài)
store.state.b.xxx // -> moduleB 的狀態(tài)

state 狀態(tài)值管理變量管理

//store 中注冊(cè)state;
const app={
state :{
a:'xxx',
b:'xxxx'
}
}
//在頁(yè)面中調(diào)用
this.$store.state.a
// 在單獨(dú)構(gòu)建的版本中輔助函數(shù)為 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭頭函數(shù)可使代碼更簡(jiǎn)練
    count: state => state.count,

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

    // 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù)
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}
//如果computer如果有多個(gè)鍵值,可以以對(duì)象的形勢(shì)表示
computed:{...mapState(...)}

//如果對(duì)state的狀態(tài)進(jìn)行計(jì)算并且在多地方應(yīng)用時(shí)間,(return this.$store.state.todos.filter(todo => todo.done).length)應(yīng)當(dāng)在srore 中注冊(cè)getters;

//注冊(cè)方法getters
const app={
 state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
}
//頁(yè)面中調(diào)用
this.$store.getters.doneTodos;

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

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}
store.getters.doneTodosCount // -> 1
//也可以傳遞任何一個(gè)頁(yè)面的參數(shù)
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

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

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 變更狀態(tài)
      state.count++
    }
  }
})
//傳遞的當(dāng)前模塊中state;
 mutations: {
    increment (state,pra) {
      // 變更狀態(tài)
      state.count=pra+10;
    }
  }
//頁(yè)面組件中調(diào)用
this.$store.commit('increment', 10)

對(duì)組件中的方法調(diào)用必須是使用commit 來(lái)調(diào)用mutations中的方法,實(shí)現(xiàn)數(shù)據(jù)的可追蹤,
在大多數(shù)情況下,載荷應(yīng)該是一個(gè)對(duì)象,這樣可以包含多個(gè)字段并且記錄的 mutation 會(huì)更易讀:

this.$store.commit('increment',{count:1})
 mutations: {
    increment (state,prams) {
      // 變更狀態(tài)
      state.count=prams.count+10;
    }
  }

mutations type名稱可以獨(dú)立出來(lái),增加代碼維護(hù)可讀性

// 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 風(fēng)格的計(jì)算屬性命名功能來(lái)使用一個(gè)常量作為函數(shù)名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

在組件中提交 Mutation
你可以在組件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 輔助函數(shù)將組件中的 methods 映射為 store.commit 調(diào)用(需要在根節(jié)點(diǎn)注入 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')`
    })
  }
}

mutations 中方法必須是同步的如果想實(shí)現(xiàn)調(diào)用異步操作可以調(diào)用Action;
Action 定義;

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})
//context 是store的上下文

Action 函數(shù)接受一個(gè)與 store 實(shí)例具有相同方法和屬性的 context 對(duì)象,因此你可以調(diào)用 context.commit 提交一個(gè) mutation,或者通過 context.statecontext.getters 來(lái)獲取 state 和 getters。當(dāng)我們?cè)谥蠼榻B到 Modules 時(shí),你就知道 context 對(duì)象為什么不是 store 實(shí)例本身了。

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

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}
//在頁(yè)面組件中調(diào)用
this.$store.dispatch('increment')
//也可以傳遞參數(shù)
// 以載荷形式分發(fā)
store.dispatch('incrementAsync', {
  amount: 10
})
actions: {
  incrementAsync({ commit },params) {
    commit('increment,params.amount')
  }
}

在組件中分發(fā) Action
你在組件中使用 this.$store.dispatch('xxx') 分發(fā) action,或者使用 mapActions 輔助函數(shù)將組件的 methods 映射為 store.dispatch 調(diào)用(需要先在根節(jié)點(diǎn)注入 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')`
    })
  }
}

[參考文件](https://vuex.vuejs.org/zh/guide/state.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容