## vuex狀態管理
`state,getter,mutation,action四個模塊
state:定義變量;
getters:獲取變量;
mutations:同步執行對變量進行的操作;
actions:異步執行對變量進行的操作;
`
### 頁面
~~~
import { mapstate, mapActions, mapMutations } from 'vuex' //導入輔助函數
~~~
### 處理形式
#### 數據state
~~~
computed: { //計算函數
// 對象形式
// ...mapstate({
// logs: state => state.logs
// })
//數組形式
...mapstate([
// 需要和state中定義的變量相同
'logs'
])
},
logs可直接使用 this.logs
~~~
#### 方法 mutations/actions
~~~
methods: { //方法
// 對象形式
// ...mapActions({
// 'addErrorLog': 'addErrorLog'
// })
// 數組形式
...mapActions([
'addErrorLog'
]),
// 對象形式
// ...mapMutations({
// 'ADD_ERROR_LOG': 'ADD_ERROR_LOG'
// })
// 數組形式
...mapMutations([
'ADD_ERROR_LOG'
])
}
~~~
# store模塊數據
~~~
const state = {
logs: []
}
const getters = {
logsGetter: (state) => {
return state.logs
}
}
const mutations = {
ADD_ERROR_LOG: (state, log) => {
state.logs.push(log)
}
}
const actions = {
addErrorLog({ commit }, log) {
commit('ADD_ERROR_LOG', log)
}
}
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
~~~