一,Vuex是什么
1. 基础定义
"Vuex是Vue.js的官方状态管理库,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。"
2. 核心概念
"Vuex的核心包含五个关键部分:
-
State:数据源,存储应用状态,类似组件的data但全局唯一
```state: { count: 0, user: null } -
Getters:相当于store的计算属性,用于派生状态
```getters: { doubleCount: state => state.count * 2 } -
Mutations:唯一能直接修改state的方法,必须是同步的
```mutations: { increment(state) { state.count++ } } -
Actions:处理异步操作,通过提交mutation来变更状态
```actions: { asyncIncrement({ commit }) { setTimeout(() => { commit('increment') }, 1000) } } -
Modules:允许将store分割成模块,每个模块拥有自己的state/mutations等"
```const moduleA = { state: () => ({ ... }), mutations: { ... } } const store = new Vuex.Store({ modules: { a: moduleA } })
3. 工作流程
Vuex的工作流程是:
- 组件通过
dispatch调用action - Action执行异步操作后,用
commit提交mutation - Mutation直接修改state
- State变化后自动重新渲染相关组件
4. 解决的问题
Vuex主要解决:
- 组件间状态共享:当多个组件需要读取同一状态时
- 状态变更追踪:需要记录状态变化历史时
- 跨组件通信:非父子组件间的通信
- 复杂状态逻辑:当组件的状态逻辑变得复杂时"
5,基本使用示例
安装 Vuex
```js
```npm install vuex --save
创建 Store
```js
```// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
doubleCount: state => state.count * 2
}
})
在组件中使用
```js
```// 访问 state
this.$store.state.count
// 调用 getter
this.$store.getters.doubleCount
// 提交 mutation
this.$store.commit('increment')
// 分发 action
this.$store.dispatch('incrementAsync')
二,Pinia是什么
1. 基础定义
Pinia 是 Vue.js 的新一代官方推荐状态管理库(Vuex 的继任者),专为 Vue 2 和 Vue 3 设计,提供更简洁、直观的 API 和完整的 TypeScript 支持。
2. 核心概念
-
State
定义应用的状态数据(类似组件的 data)。
```js
```import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
user: null
})
});
-
Getters
计算派生状态(类似组件的 computed)。
```js
```getters: {
doubleCount: (state) => state.count * 2
}
-
Actions
包含同步/异步逻辑,直接修改 state(无需 commit)。
```js
```actions: {
increment() {
this.count++; // 直接修改 state
},
async fetchUser() {
const user = await api.getUser();
this.user = user;
}
}
3.为什么选择 Pinia?
- 更符合直觉:直接修改 state,无需区分
commit/dispatch。 - 更好的 TS 支持:自动推断类型,减少类型声明代码。
- 更轻量:适合中小型项目,避免 Vuex 的过度设计。
- 未来趋势:Vue 官方推荐,Vuex 将逐步维护。
4.基本使用示例
安装 Pinia
```js
```npm install pinia
# 或
yarn add pinia
创建 Store
```js
```// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
}
}
});
在组件中使用
```js
```<script setup>
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
</script>
<template>
<div>Count: {{ counter.count }}</div>
<div>Double: {{ counter.double }}</div>
<button @click="counter.increment()">+1</button>
</template>