vue Pinia使用指南

1.安装pinia

npm install pinia

2.基本配置

main.js中,app.use(createPinia()) 引入

3.创建store  

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Pinia User'
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    doubleCountPlusOne() {
      return this.doubleCount + 1
    }
  },
  actions: {
    increment() {
      this.count++
    },
    async incrementAsync() {
      await new Promise(resolve => setTimeout(resolve, 1000))
      this.increment()
    }
  }
})

4. 在组件中使用store

import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()

5.状态修改方式

  1.直接修改:counter.count++

  2.使用$patch:counter.$patch({ count: counter.count + 1 })

  3.重置状态:counter.$reset()

6.订阅状态变化

counter.$subscribe((mutation, state) => {
  console.log('状态变化:', mutation, state)
})

7.组合式api中,使用 storeToRefs 解构保持响应性

import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()
const { count, name } = storeToRefs(counter)

8.Pinia 天然支持模块化,只需创建不同的 store 文件

9.持久化存储

  1.可以使用插件实现状态持久化,如 pinia-plugin-persistedstate:

//配置
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

----------------------------------------------------------------------------------
//store中启用
export const useUserStore = defineStore('user', {
  state: () => ({
    userData: null
  }),
  persist: true
})

  2.单个store中单独持久化:

export const use*** = defineStore('***', {
  persist: {
    storage: Local,
  },
 state:..........
posted @ 2025-10-10 15:50  榆木脑袋敲啊敲  阅读(24)  评论(0)    收藏  举报