赞
踩
Vuex 和 Pinia 均是 Vue.js 的状态管理库,它们为 Vue 应用程序提供了一种集中式的、可预测的状态管理解决方案。
Vuex 是 Vue.js 官方推荐的状态管理库之一。它的核心概念包括 state、mutation、action 和 getter。其中,state 代表应用程序的状态数据,在 Vuex 中存储为唯一的来源,mutation 用于修改状态数据并确保数据变化的可追踪性,action 用于处理异步操作或组合多个 mutation 操作,getter 可以让我们对 state 进行计算和派生,并使其变得更加易于访问。一个 Vuex store 实例是一个全局 JavaScript 对象,可以在所有组件中通过注入来进行访问和操作。
安装:npm install pinia
或 yarn add pinia
引入注册:
Vue3的引入方法main.
app.vue
- <template>
- <div>pinia-current:{{ Test.current }}</div>
- <div>pinia-name:{{ Test.name }}</div>
- </template>
-
- <script setup lang="ts">
- import { useTestStore } from "./store";
-
- const Test = useTestStore();
- </script>
-
- <style lang="scss" scoped></style>
推荐使用函数形式 可以自定义修改逻辑
- <template>
- <div>pinia-current:{{ Test.current }}</div>
- <div>pinia-name:{{ Test.name }}</div>
- <div style="display: flex; flex-direction: column">
- <button @click="funChange">工厂函数实现批量change</button>
- </template>
-
- <script setup lang="ts">
- import { useTestStore } from "./store";
-
- const Test = useTestStore();
-
- const funChange = () => {
- Test.$patch((state) => {
- (state.current = 999), (state.name = "小3");
- });
- };
- </script>
-
- <style lang="scss" scoped></style>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。