vue 狀態(tài)管理vuex

在viwe同級別建立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 中注冊state;
const app={
state :{
a:'xxx',
b:'xxxx'
}
}
//在頁面中調(diào)用
this.$store.state.a
// 在單獨(dú)構(gòu)建的版本中輔助函數(shù)為 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: 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
    }
  })
}
//如果computer如果有多個(gè)鍵值衣迷,可以以對象的形勢表示
computed:{...mapState(...)}

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

//注冊方法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)
    }
  }
}
//頁面中調(diào)用
this.$store.getters.doneTodos;

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

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}
store.getters.doneTodosCount // -> 1
//也可以傳遞任何一個(gè)頁面的參數(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;
    }
  }
//頁面組件中調(diào)用
this.$store.commit('increment', 10)

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

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

mutations type名稱可以獨(dú)立出來纺腊,增加代碼維護(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ì)算屬性命名功能來使用一個(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 對象,因此你可以調(diào)用 context.commit 提交一個(gè) mutation壹粟,或者通過 context.statecontext.getters 來獲取 state 和 getters拜隧。當(dāng)我們在之后介紹到 Modules 時(shí),你就知道 context 對象為什么不是 store 實(shí)例本身了趁仙。

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

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}
//在頁面組件中調(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)容合作請聯(lián)系作者
  • 序言:七十年代末干奢,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子盏袄,更是在濱河造成了極大的恐慌忿峻,老刑警劉巖薄啥,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異逛尚,居然都是意外死亡垄惧,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進(jìn)店門黑低,熙熙樓的掌柜王于貴愁眉苦臉地迎上來赘艳,“玉大人,你說我怎么就攤上這事克握±俟埽” “怎么了?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵菩暗,是天一觀的道長掰曾。 經(jīng)常有香客問我,道長停团,這世上最難降的妖魔是什么旷坦? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮佑稠,結(jié)果婚禮上秒梅,老公的妹妹穿的比我還像新娘。我一直安慰自己舌胶,他們只是感情好捆蜀,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著幔嫂,像睡著了一般辆它。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上履恩,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天锰茉,我揣著相機(jī)與錄音,去河邊找鬼切心。 笑死飒筑,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的绽昏。 我是一名探鬼主播扬霜,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼而涉!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起联予,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤啼县,失蹤者是張志新(化名)和其女友劉穎材原,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體季眷,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡余蟹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了子刮。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片威酒。...
    茶點(diǎn)故事閱讀 40,444評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖挺峡,靈堂內(nèi)的尸體忽然破棺而出葵孤,到底是詐尸還是另有隱情,我是刑警寧澤橱赠,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布尤仍,位于F島的核電站,受9級特大地震影響狭姨,放射性物質(zhì)發(fā)生泄漏宰啦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一饼拍、第九天 我趴在偏房一處隱蔽的房頂上張望赡模。 院中可真熱鬧,春花似錦师抄、人聲如沸漓柑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽欺缘。三九已至,卻和暖如春挤安,著一層夾襖步出監(jiān)牢的瞬間谚殊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工蛤铜, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留嫩絮,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓围肥,卻偏偏與公主長得像剿干,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子穆刻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容