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

897 B
Raw Blame History

Pinia 状态管理

学习目标

  • 了解状态管理必要性
  • 掌握 Pinia 基本用法
  • 学会模块化管理

Pinia 简介

Pinia 是 Vue 3 官方推荐的状态管理库,替代 Vuex。

定义 Store

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
    state: () => ({
        count: 0
    }),
    getters: {
        doubled: (state) => state.count * 2
    },
    actions: {
        increment() {
            this.count++
        }
    }
})

使用 Store

<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. 使用持久化插件