安装
指令
npm install vuex
基础结构
详细使用:官方介绍
import { createStore } from 'vuex'
export default createStore({
state: {
count:1
},
mutations: {
},
actions: {
},
modules: {
}
})
在组件或页面中使用
因为不使用this
,所以vuex有些不同
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// 在 computed 函数中访问 state
count: computed(() => store.state.count),
// 在 computed 函数中访问 getter
double: computed(() => store.getters.double)
// 使用 mutation
increment: () => store.commit('increment'),
// 使用 action
asyncIncrement: () => store.dispatch('asyncIncrement')
}
}
}