53 lines
897 B
Markdown
53 lines
897 B
Markdown
# Pinia 状态管理
|
||
|
||
## 学习目标
|
||
- 了解状态管理必要性
|
||
- 掌握 Pinia 基本用法
|
||
- 学会模块化管理
|
||
|
||
## Pinia 简介
|
||
|
||
Pinia 是 Vue 3 官方推荐的状态管理库,替代 Vuex。
|
||
|
||
## 定义 Store
|
||
|
||
```typescript
|
||
import { defineStore } from 'pinia'
|
||
|
||
export const useCounterStore = defineStore('counter', {
|
||
state: () => ({
|
||
count: 0
|
||
}),
|
||
getters: {
|
||
doubled: (state) => state.count * 2
|
||
},
|
||
actions: {
|
||
increment() {
|
||
this.count++
|
||
}
|
||
}
|
||
})
|
||
```
|
||
|
||
## 使用 Store
|
||
|
||
```vue
|
||
<script setup>
|
||
import { useCounterStore } from '@/stores/counter'
|
||
|
||
const counter = useCounterStore()
|
||
</script>
|
||
|
||
<template>
|
||
<button @click="counter.increment">
|
||
{{ counter.count }} × 2 = {{ counter.doubled }}
|
||
</button>
|
||
</template>
|
||
```
|
||
|
||
## 动手练习
|
||
|
||
1. 创建用户状态 Store
|
||
2. 实现登录状态管理
|
||
3. 使用持久化插件
|