Vuex 在 Vue3 中的使用方式与 Vue2 相比有一些重要区别,主要源于 Vue3 本身的 API 变化(如 Composition API 的引入)以及 Vuex 4.x 对 Vue3 的适配。以下是核心区别:
1. 安装与引入方式
- Vue2 + Vuex 3.x
通过Vue.use(Vuex)
安装,在根实例中注入 store:
import Vue from 'vue'
import Vuex from 'vuex'
import store from './store'Vue.use(Vuex) // 必须调用 use 安装new Vue({el: '#app',store, // 注入根实例render: h => h(App)
})
- Vue3 + Vuex 4.x
无需调用Vue.use()
,直接通过createApp
的use()
方法安装:
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'createApp(App).use(store) // 直接通过 app.use() 安装.mount('#app')
2. 在组件中访问 Store 的方式
- Vue2(Options API)
通过this.$store
访问,结合mapState
、mapGetters
等辅助函数:
export default {computed: {...mapState(['count']),...mapGetters(['doubleCount'])},methods: {...mapMutations(['increment']),...mapActions(['asyncIncrement'])}
}
- Vue3(Composition API)
需通过useStore
函数获取 store 实例(替代this.$store
),且辅助函数使用方式不同:
<script setup>
import { useStore } from 'vuex'
import { computed } from 'vue'const store = useStore() // 获取 store 实例// 访问状态(替代 mapState)
const count = computed(() => store.state.count)// 访问 getters(替代 mapGetters)
const doubleCount = computed(() => store.getters.doubleCount)// 调用 mutations(替代 mapMutations)
const increment = () => store.commit('increment')// 调用 actions(替代 mapActions)
const asyncIncrement = () => store.dispatch('asyncIncrement')
</script>
3. TypeScript 支持
- Vue2 + Vuex 3.x
对 TypeScript 支持较弱,需要手动声明类型,类型推断不完善。 - Vue3 + Vuex 4.x
原生支持 TypeScript,可通过泛型指定 store 类型,获得完整的类型推断:
// store/index.ts
import { createStore, Store } from 'vuex'
import { InjectionKey } from 'vue'// 定义状态类型
export interface State {count: number
}// 定义注入键(用于 TypeScript 类型推断)
export const key: InjectionKey<Store<State>> = Symbol()export default createStore<State>({state: { count: 0 }
})// 在组件中使用
import { useStore } from 'vuex'
import { key, State } from './store'const store = useStore(key) // 传入键以获得类型提示
4. 响应式处理
- Vue2
Vuex 状态依赖 Vue2 的响应式系统(Object.defineProperty
),需遵循 Vue2 的响应式规则(如新增属性需用Vue.set
)。 - Vue3
Vuex 4.x 适配 Vue3 的响应式系统(Proxy
),状态的响应式处理更灵活,无需额外处理新增属性的响应性。
5. 开发工具支持
- Vuex 4.x 对 Vue3 DevTools 有更好的支持,可更清晰地追踪状态变化和调试。
6. 废弃与保留的 API
- 保留的核心概念:
state
、getters
、mutations
、actions
、modules
的核心逻辑不变。 - 废弃的用法:Vue3 中不再支持 Vue2 选项式 API 中依赖
this
的写法(如this.$store
在 Composition API 中不可用)。
总结
- 安装方式从
Vue.use(Vuex)
改为app.use(store)
- 组件中通过
useStore()
获取实例,替代this.$store
- 更好的 TypeScript 支持和 Vue3 响应式系统适配