简单vuex使用
核心 :state getters mutations actions
state
唯一数据源
getters
可以认为是 store 的计算属性
mutations
更改 Vuex 的 store 中的状态
actions
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作
使用
const commonStore = {
state:{
list:[]
},
getters:{
getList(state) {
return state.list
},
},
mutations:{
SET_LIST(state, value) {
state.list= value
},
},
actions:{
async fetchList({commit}) {
const result = await getList() || []
commit('SET_LIST', result)
},
}
}
export default commonStore
组件中使用
分发
store.dispatch('commonStore/fetchList') // 光源类型
取值
const list = computed(() => store.getters['commonStore/getList'])