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)

相关推荐
sir.山1 天前
在 Vue 3 项目中使用 Mock 数据
前端·vue.js·vue3·vite
你别说话了1 天前
Vue项目解决跨域
前端·javascript·vue.js
学习星球2 天前
Solid.js 实战:拆解官方 RealWorld 项目
开发语言·javascript·vue.js
尚可签2 天前
基于 Spring Boot + Vue 的 AI 智能在线订餐系统
vue.js·人工智能·spring boot
MacroZheng2 天前
腾讯又开源了一个新项目,用起来真优雅!
前端·vue.js·人工智能
张人玉2 天前
基于 Vue 3 + ECharts + Three.js + Express + SQLite——智慧城市数字孪生可视化平台
javascript·vue.js·信息可视化·sqlite·echarts
山川志~2 天前
Vue + Element UI 实战:如何实现表格时间、金额字段排序
vue.js·ui·elementui
_codemonster3 天前
Vue中的ref和reactive到底在干嘛
前端·javascript·vue.js
前端fighter3 天前
线上崩溃?使用 TRAE Work 5分钟把混淆日志翻译成人话并输出复盘报告
前端·vue.js·程序员
常宇佳3 天前
vue3 实战系列之无法识别vue组件
前端·javascript·vue.js