在 Vue3 中使用 Vuex 进行状态管理,主要通过 Composition API 中的 useStore
方法获取 store 实例,再结合相关 API 操作状态。以下是详细步骤和示例:
确保已安装 Vuex 4.x(Vue3 兼容版本):
npm install vuex@4 --save
假设已创建好 Vuex store(src/store/index.js
):
// src/store/index.js
import { createStore } from 'vuex'
export default createStore({
state() {
return {
count: 0,
user: { name: '访客' }
}
},
getters: {
doubleCount(state) {
return state.count * 2
},
userName(state) {
return state.user.name
}
},
mutations: {
increment(state) {
state.count++
},
setUser(state, payload) {
state.user = payload
}
},
actions: {
async incrementAsync({ commit }, delay) {
await new Promise(resolve => setTimeout(resolve, delay))
commit('increment')
},
async fetchUser({ commit }) {
// 模拟 API 请求
const mockUser = { name: '张三' }
commit('setUser', mockUser)
}
}
})
在 <script setup>
中通过 useStore
访问 store,配合 computed
保持响应性:
<template>
<div class="vuex-demo">
<h3>状态管理示例</h3>
<!-- 访问 state 和 getters -->
<p>当前计数:{{ count }}</p>
<p>计数加倍:{{ doubleCount }}</p>
<p>当前用户:{{ userName }}</p>
<!-- 操作按钮 -->
<button @click="handleIncrement">+1(同步)</button>
<button @click="handleIncrementAsync">+1(延迟1秒)</button>
<button @click="handleFetchUser">加载用户</button>
</div>
</template>
<script setup>
import { useStore } from 'vuex'
import { computed } from 'vue'
// 1. 获取 store 实例
const store = useStore()
// 2. 访问 state(通过 computed 保持响应式)
const count = computed(() => store.state.count)
const userName = computed(() => store.state.user.name)
// 3. 访问 getters
const doubleCount = computed(() => store.getters.doubleCount)
// 4. 提交 mutations(同步修改状态)
const handleIncrement = () => {
store.commit('increment') // 调用 mutation
}
// 5. 调用 actions(处理异步操作)
const handleIncrementAsync = () => {
store.dispatch('incrementAsync', 1000) // 传递参数(延迟时间)
}
const handleFetchUser = () => {
store.dispatch('fetchUser') // 调用异步 action
}
</script>
<style scoped>
button {
margin: 0 8px;
padding: 4px 8px;
}
</style>
useStore()
替代 Vue2 中的 this.$store
,这是 Composition API 中访问 store 的唯一方式。computed
包裹 store.state.xxx
,确保状态变化时组件能响应式更新:const count = computed(() => store.state.count)computed
包裹 store.getters.xxx
:const doubleCount = computed(() => store.getters.doubleCount)store.commit('mutationName', payload)
提交同步操作:// 无参数
store.commit('increment')
// 带参数
store.commit('setUser', { name: '李四' })store.dispatch('actionName', payload)
处理异步操作:// 无参数
store.dispatch('fetchUser')
// 带参数
store.dispatch('incrementAsync', 1000)如果 store 拆分了命名空间模块(如 cart
模块):
// store/index.js 中添加
modules: {
cart: {
namespaced: true, // 启用命名空间
state: () => ({ items: [] }),
mutations: {
addItem(state, item) {
state.items.push(item)
}
}
}
}
在组件中访问时需指定模块名:
// 访问模块 state
const cartItems = computed(() => store.state.cart.items)
// 提交模块 mutation
const addToCart = () => {
store.commit('cart/addItem', { id: 1, name: '商品' })
}
若仍使用 Options API,可沿用 Vue2 的映射方式:
<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
computed: {
...mapState(['count', 'user']),
...mapGetters(['doubleCount'])
},
methods: {
...mapMutations(['increment']),
...mapActions(['incrementAsync', 'fetchUser'])
},
mounted() {
console.log(this.count) // 访问映射的状态
}
}
</script>
Vue3 中使用 Vuex 的核心流程:
useStore()
获取 store 实例computed
包装 state
和 getters
确保响应性store.commit()
提交 mutations(同步)store.dispatch()
调用 actions(异步)这种方式完全适配 Vue3 的 Composition API,同时保留了 Vuex 集中式状态管理的核心优势。如果是新项目,建议考虑 Vue 官方推荐的 Pinia(Vuex 的继任者),其 API 更简洁,更适合 Vue3。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。