vuex、pinia和Dva里的方法

1. vuex: state、getter、actions(dispatch)、mutations(commit)
2. pinia: state、getters、actions(params)
跟vuex差不多,就是没有mutations,直接在actions里修改数据: this.xxx = xxx
使用 async await 请求数据,跟在普通js中一样
3. Dva: state、 effects(call)、reducers(put)

Hooks、Vuex Pinia 都是前端开发中重要的工具,但它们的用途应用场景有所不同。 ### 概念用途 - **Hooks**:在 React 中,Hooks 是一种新特性,让开发者可以在不编写 `class` 的情况下使用 `state` 以及其他 React 特性,它提供了一种更简洁、更直观的方式来使用 React 的特性,从简单的状态管理到复杂的副作用处理,Hooks 都能提供优雅的解决方案。在 Vue 3 中,Hooks 也是组合式 API 的灵感来源,它借助 `setup` 语法糖,使得代码逻辑可以更好地复用组织 [^3]。 - **Vuex**:是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。适用于中大型单页面应用,用于管理多个组件共享的状态 [^1]。 - **Pinia**:同样是 Vue 的状态管理库,它是 Vuex 的替代方案,相比于 VuexPinia 更加简洁,支持直接修改状态,并且调试工具能够记录到每一次 `state` 的变化,适合新项目使用 [^1][^2]。 ### 使用方式 - **Hooks**:一般使用 `use` 开头,例如 `useState`、`useEffect` 等。在 React 函数组件中可以直接调用,每次渲染都会重新调用 Hooks 函数。在 Vue 3 中,`setup` 语法糖仅被调用一次 [^3]。 ```jsx // React Hooks 示例 import React, { useState } from 'react'; function Example() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } ``` - **Vuex**:需要创建一个 store 实例,在组件中通过 `this.$store` 来访问修改状态。 ```javascript // 创建 store import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } } }); export default store; ``` ```vue <template> <div> <p>{{ $store.state.count }}</p> <button @click="$store.commit('increment')">Increment</button> </div> </template> ``` - **Pinia**:创建 store 并在组件中使用,支持直接修改状态。 ```javascript // 创建 store import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++; } } }); ``` ```vue <template> <div> <p>{{ counterStore.count }}</p> <button @click="counterStore.increment()">Increment</button> </div> </template> <script setup> import { useCounterStore } from './store'; const counterStore = useCounterStore(); </script> ``` ### 特性差异 - **Hooks**:有闭包陷阱的问题,但能让函数组件更灵活地使用状态副作用,提高代码复用性 [^3]。 - **Vuex**:采用集中式状态管理,通过 `mutations`、`actions` `getters` 来管理状态的变化,保证状态变化可预测。 - **Pinia**:语法更简洁,支持直接修改状态,调试工具能更好地记录状态变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值