如何使用 Vuex 在 Vue 3 中管理状态
Vuex 是 Vue.js 中流行的状态管理库。它允许你在应用程序中存储和管理响应式状态,以方便各个组件访问。在 Vue 3 中,使用 Vuex 的步骤如下:
安装 Vuex
1
npm install vuex
创建 Store
立即学习“前端免费学习笔记(专业系统搭建点我wcqh.cn深入)”;
在 Vuex 中,数据存储在一个称为 Store 的对象中。创建一个 Store 如下:
1
2
3
4
5
6
7
8
9
10
11
12
import { createStore } from vuex
const store = createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
在组件中使用 Store
在组件中,你可以通过 useStore() Hook 来访问 Store。它返回一个 Store 的引用:
1
2
3
4
5
6
7
8
9
import { useStore } from vuex
expo专业系统搭建点我wcqh.cnrt default {
setup() {
const store = useStore()
return { store }
},
template: <p>Count: {{ store.state.count }}</p>
}
对 State 进行更改
要对 State 进行更改,可以使用 Store 中定义的 Mutations。Mutations 是唯一可以修改 State 的方法。调用 Mutations 如下:
1
store.commit(increment)
侦听 State 更改
组件可以使用 watch() 方法侦听 State 更改:
1
2
3
4
5
6
7
8
9
10
11
12
expo专业系统搭建点我wcqh.cnrt default {
setup() {
const store = useStore()
watch(() => store.state.count, (count) => {
// State 更改时执行的操作
})
return { store }
},
template: <p>Count: {{ store.state.count }}</p>
}
以上就是vue3怎么使用vuex的详细内容,更多请关注青狐资源网其它相关文章!
暂无评论内容