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)

相关推荐
酷炫码神6 小时前
Day 8|Vue3 响应式:告别手动操作 DOM,让数据驱动界面
javascript·vue.js·ecmascript
星光不问赶路人8 小时前
Vue 3 对象监听与快照:ref 和 reactive 的关键差异
前端·vue.js
稻草人4788 小时前
Vue3.0项目创建步骤
vue.js
Bug收容所9 小时前
Vue+js Day2
前端·javascript·vue.js
honkun611 小时前
vue 下拉树组件 vxe-table-select 实现分页多选
前端·javascript·vue.js
溪语流沙12 小时前
【Web全栈进阶】监控与告警:线上系统的“体检报告”
前端·vue.js·python·fastapi
卤蛋fg613 小时前
vue 下拉树组件 vxe-table-select 实现分页多选
vue.js
u01110267517 小时前
Vue 页面离开后还在轮询?统一清理计时器、监听器与观察器
前端·javascript·vue.js
大猩猩X17 小时前
vue 表格组件 vxe-table 实现多行编辑,支持增删改查与校验
前端·javascript·vue.js·vxe-table
ss27317 小时前
基于springboot+vue+mysql「校园二手教材循环交易」小程序,三端全跑通
vue.js·spring boot·mysql