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)

相关推荐
~牧马~2 小时前
【记录63】electron打包vue项目之踩坑
vue.js·electron·electron与node兼容
计算机学姐3 小时前
基于SpringBoot的电影点评交流平台【协同过滤推荐算法+数据可视化统计】
java·vue.js·spring boot·spring·信息可视化·echarts·推荐算法
心柠4 小时前
vue3相关知识总结
前端·javascript·vue.js
a1117765 小时前
图书借阅管理系统(FastAPI + Vue)
前端·vue.js·fastapi
极致♀雨5 小时前
vue2+elementUI table表格勾选行冻结/置顶
前端·javascript·vue.js·elementui
林shir5 小时前
3-15-前端Web实战(Vue工程化+ElementPlus)
前端·javascript·vue.js
Hi_kenyon8 小时前
Ref和Reactive都是什么时候使用?
前端·javascript·vue.js
zhougl99610 小时前
Vue 中使用 WebSocket
前端·vue.js·websocket
半梅芒果干10 小时前
vue3 实现无缝循环滚动
前端·javascript·vue.js
雯0609~11 小时前
hiprint-官网vue完整版本+实现客户端配置+可实现直接打印(在html版本增加了条形码、二维码拖拽等)
前端·javascript·vue.js