- 學(xué)習(xí)資源: https://vuex.vuejs.org/zh-cn/
介紹
- Vuex是為Vue.js應(yīng)用程序開(kāi)發(fā)的狀態(tài)管理模式,采用集中式存儲(chǔ)管理所有組件的狀態(tài),通俗來(lái)講,是為了實(shí)現(xiàn)任意組件之間的通信,其主要包含四個(gè)模塊:
image - state:保存整個(gè)應(yīng)用的狀態(tài)(數(shù)據(jù))
- mutations:改變狀態(tài)的唯一方式,同步操作
- actions:類似mutation,異步操作
- vue components:vue組件
安裝
- 在項(xiàng)目目錄下使用npm或cnpm:
npm install vuex --save
image
- 安裝完成后再次下載依賴
npm install
使用
-
安裝完成后,建議在src目錄下單獨(dú)創(chuàng)建一個(gè)文件夾,用于保存vuex的js腳本文件
image - 在文件中引入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
- 使用引入后,切記引用vuex
Vue.use(Vuex)
image
Vuex倡導(dǎo)存、讀、寫分離
State(存)
- state負(fù)責(zé)存儲(chǔ)整個(gè)應(yīng)用的狀態(tài)數(shù)據(jù),在需要使用的時(shí)候在根節(jié)點(diǎn)注入store對(duì)象,注入后使用
this.$store.state獲取狀態(tài)
image
image
image
- 重命名該狀態(tài):
-
通過(guò)計(jì)算屬性computed直接賦值:
image -
通過(guò)mapState進(jìn)行賦值:
computed: mapState({ nameFromMapState: state => state.person.name, ageFromMapState: state => state.person.age, genderFromMapState: state => state.person.gender, }) -
mapState的更簡(jiǎn)單寫法:若映射的屬性名稱與state的子節(jié)點(diǎn)名稱相同時(shí),可采用字符串?dāng)?shù)組的形式簡(jiǎn)寫
mapState(['person','time']) //映射this.person為store.state.person
-
getters(讀)
- getter屬性可以認(rèn)為是store的計(jì)算屬性,它接收state作為第一個(gè)參數(shù)
image
- getters暴露一
個(gè)store.getters對(duì)象,通過(guò)這個(gè)對(duì)象訪問(wèn)其內(nèi)部數(shù)據(jù)
this.$store.getters.getYear
- getters也可用mapGetters進(jìn)行改名:
mapGetters({
yearFromMapGetters: 'getYear',
monthFromMapGetters: 'getMonth',
dayFromMapGetters: 'getDay',
})
mutations
- 唯一更改store中狀態(tài)的方法