Files
chunyu_project/media/learn/courses/15/chapters/64.md
T
2026-08-05 23:59:15 +08:00

53 lines
897 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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. 使用持久化插件