Pinia入门

文章目录

  • [什么是 Pinia](#什么是 Pinia)
  • [集成 Pinia 到 Vue 项目](#集成 Pinia 到 Vue 项目)
  • 基础使用
  • [Getters 实现](#Getters 实现)
  • [异步 Actions](#异步 Actions)
  • [响应式解构 storeToRefs](#响应式解构 storeToRefs)
  • Pinia调试
  • [持久化插件 pinia-plugin-persistedstate](#持久化插件 pinia-plugin-persistedstate)

什么是 Pinia

Pinia 是 Vue 官方推荐的新一代状态管理工具,旨在替代 Vuex。其主要优势包括:

  • 更简单的 API:移除了 mutation,逻辑更直观
  • 组合式 API 风格:与 Vue 3 的 <script setup> 语法天然契合
  • 无 modules 概念:每个 store 都是独立模块,结构更扁平
  • TypeScript 友好:提供出色的类型推断支持

集成 Pinia 到 Vue 项目

  1. 使用 Vite 创建 Vue 3 项目:
bash 复制代码
npm create vue@latest
  1. 安装 Pinia:
bash 复制代码
npm install pinia
  1. 在 main.js 中注册:
js 复制代码
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')

基础使用

计数器案例

  1. 定义 Store(stores/counter.js)
js 复制代码
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  // state
  state: () => ({
    count: 0
  }),
  // actions(同步或异步)
  actions: {
    increment() {
      this.count++
    }
  }
})
  1. 在组件中使用
html 复制代码
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>

<template>
  <p>{{ counter.count }}</p>
  <button @click="counter.increment">+1</button>
</template>

Getters 实现

Pinia 中的 getters 等价于 Vue 的 computed

js 复制代码
getters: {
  doubleCount: (state) => state.count * 2
}

异步 Actions

Action 支持直接编写异步逻辑,无需额外处理:

js 复制代码
actions: {
  async fetchChannels() {
    const res = await fetch('http://geek.itheima.net/v1_0/channels')
    const data = await res.json()
    this.channels = data.data.channels
  }
}

在组件中调用:

js 复制代码
onMounted(() => {
  store.fetchChannels()
})

响应式解构 storeToRefs

直接解构 store 会丢失响应性。使用 storeToRefs 保持响应式:

js 复制代码
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'

const store = useCounterStore()
const { count } = storeToRefs(store) // 响应式
const { increment } = store // 方法无需 ref

Pinia调试

Vue官方的 dev-tools 调试工具 对 Pinia直接支持,可以直接进行调试

持久化插件 pinia-plugin-persistedstate

官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/

实现状态持久化(如保存到 localStorage):

  1. 安装插件:
bash 复制代码
npm install pinia-plugin-persistedstate
  1. 在 main.js 中启用:
js 复制代码
import persist from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(persist)
app.use(pinia)
  1. 在 store 中开启持久化:
js 复制代码
export const useUserStore = defineStore('user', {
  state: () => ({ token: '' }),
  persist: true // 启用持久化
})

默认使用 localStorage,也可自定义存储方式(如 sessionStorage)

相关推荐
林恒smileZAZ1 天前
Vue<前端页面版本检测>
前端·javascript·vue.js
我是Superman丶1 天前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
Cobyte1 天前
3.响应式系统基础:从发布订阅模式的角度理解 Vue2 的数据响应式原理
前端·javascript·vue.js
军军君011 天前
Three.js基础功能学习十八:智能黑板实现实例五
前端·javascript·vue.js·3d·typescript·前端框架·threejs
禅思院1 天前
前端架构演进:基于AST的常量模块自动化迁移实践
前端·vue.js·前端框架
许杰小刀1 天前
FastAPI + Vue 前后端分离实战:我的项目结构“避坑指南”
前端·vue.js·fastapi
walking9571 天前
Vue3 日历组件选型指南:五大主流方案深度解析
前端·vue.js·面试
英俊潇洒美少年1 天前
Vue、React.lazy、React 19 异步组件核心区别
javascript·vue.js·react.js
快乐小土豆~~1 天前
echarts柱状图的X轴label过长被重叠覆盖
前端·javascript·vue.js·echarts
儒雅的烤地瓜1 天前
Vue | Vue3中<script setup>用法详解
vue.js·vue3·选项式api·组合式 api·setup方法·<script setup>