Vuex有五個核心概念:
state, getters, mutations, actions, modules。
1. state:vuex的基本資料,用來存儲變量
state: {
userId: '',
name: '',
token: '',
}
在vue中使用 this.$store.state.userId
2. geeter:從基本資料(state)派生的資料,相當于state的計算屬性,具有傳回值的方法
getter: {
userIdDouble: function(state){
return state.userId * 2
在vue中使用 this.$store.getters.userIdDouble
3. mutation:送出更新資料的方法,必須是同步的(如果需要異步使用action)。每個 mutation 都有一個字元串的 事件類型 (type) 和 一個 回調函數 (handler)。
mutations: {
SET_USER: (state, userId) => {
state.userId = userId
},
SET_TOKEN: (state, token) => {
// console.log(token)
state.token = token
}
},
commit:同步操作,寫法: this.$store.commit(‘mutations方法名’,值)
列如
this.$store.commit('SET_USER','123456')
回調函數就是我們實際進行狀态更改的地方,并且它會接受 state 作為第一個參數,送出載荷作為第二個參數。
4. action:和mutation的功能大緻相同,不同之處在于 ==》1. Action 送出的是 mutation,而不是直接變更狀态。 2. Action 可以包含任意異步操作。