在 vue 3 中使用 vuex:安装 vuex:npm install vuex创建 vuex store:const store = createstore({ state, getters, mutations, actions })在组件中使用 vuex:const store = usestore()
Vuex 在 Vue 3 中的使用
Vuex 是一种状态管理库,用于在 Vue 应用程序中管理全局状态。在 Vue 3 中,Vuex 进行了重写,以更好地与 Composition API 和 Proxy API 一起使用。
安装 Vuex
使用 npm 安装 Vuex:
立即学习“前端免费学习笔记(深入)”;
npm install vuex
创建 Store
创建一个 Vuex Store 实例:
import { createStore } from 'vuex'
const store = createStore({
state: {
count: 0
},
getters: {
doubleCount: (state) => state.count * 2
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
在组件中使用 Vuex
使用 useStore 钩子在组件中访问 Store:
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
const count = store.state.count
const doubleCount = store.getters.doubleCount
const increment = () => {
store.commit('increment')
}
const incrementAsync = () => {
store.dispatch('incrementAsync')
}
return { count, doubleCount, increment, incrementAsync }
}
}