在 Vue 3 中使用 Vuex 管理状态的步骤如下:安装 Vuex 包。创建一个 Store 对象,存储应用程序状态。使用 useStore() 钩子在组件中访问 Store。通过 Store 中定义的 Mutations 修改 State。使用 watch() 方法侦听 State 更改。

如何使用 Vuex 在 Vue 3 中管理状态
Vuex 是 Vue.js 中流行的状态管理库。它允许你在应用程序中存储和管理响应式状态,以方便各个组件访问。在 Vue 3 中,使用 Vuex 的步骤如下:
-
安装 Vuex
npm install vuex
-
创建 Store
立即学习“前端免费学习笔记(深入)”;
在 Vuex 中,数据存储在一个称为 Store 的对象中。创建一个 Store 如下:
import { createStore } from 'vuex' const store = createStore({ state: { count: 0 }, mutations: { increment(state) { state.count++ } } }) -
在组件中使用 Store
在组件中,你可以通过
useStore()Hook 来访问 Store。它返回一个 Store 的引用:import { useStore } from 'vuex' export default { setup() { const store = useStore() return { store } }, template: 'Count: {{ store.state.count }}
' } -
对 State 进行更改
要对 State 进行更改,可以使用 Store 中定义的 Mutations。Mutations 是唯一可以修改 State 的方法。调用 Mutations 如下:
store.commit('increment') -
侦听 State 更改
组件可以使用
watch()方法侦听 State 更改:export default { setup() { const store = useStore() watch(() => store.state.count, (count) => { // State 更改时执行的操作 }) return { store } }, template: 'Count: {{ store.state.count }}
' }










