Pinia的持久化存储pinia-plugin-persist

1,249 阅读2分钟

pinia 和 vuex 一样,数据是短时的,只要一刷新页面,数据就会恢复成初始状态,为了避免这个问题,可以对其采用持久化保存方法

使用官方推荐的插件去实现持久化存储,这样更便捷,省时省力。插件为 pinia-plugin-persist,当然,实现持久化存储的插件肯定不止这一种,想用别的也可以,例如 pinia-plugin-persistedstate

1. 安装插件

安装 pinia-plugin-persist

yarn add pinia-plugin-persist
# 或者使用 npm
npm install pinia-plugin-persist

2. 引入插件

在 main.ts 中引入

引入 pinia-plugin-persist

import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'

// 下面这3行
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPersist)

createApp(App).use(pinia).mount('#app')

3. 使用插件

方式1:默认保存

下面这种写法会将当前模块中的所有数据都进行持久化保存,默认保存在 sessionStorage 中, key 为模块 id,刷新页面不需要手动读取数据,插件会自动读取

store/user.ts

import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    name: null,
    age: null,
    sex: null,
  }),
  persist: {
    enabled: true // true 表示开启持久化保存
  }
})

方式2:设置 key 、指定保存内容

你可以主动设置 key 名,也可以指定哪些数据保存,默认会保存当前模块全部数据。

store/user.ts

export const useUserStore = defineStore('storeUser', {
  state: () => ({
    name: null,
    age: null,
    sex: null,
  }),
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user',
        storage: localStorage,
        paths: ['name'] 
      },
    ],
  },
})

你甚至可以对不同数据设置不同的本地存储方式

store/user.ts

export const useUserStore = defineStore('storeUser', {
  state: () => ({
    name: null,
    age: null,
    sex: null,
  }),
  persist: {
    enabled: true,
    strategies: [
      { storage: sessionStorage, paths: ['name'] },
      { storage: localStorage, paths: ['age'] },
    ],
  },
})

方式3:保存到 cookie

保存到 cookie 中当然也是可以的,不过需要手动添加 cookie 的保存方式,同样,此处也是推荐使用插件 js-cookie 来完成

npm install js-cookie

store/user.ts

import Cookies from 'js-cookie'

// 手动添加cookie
const cookiesStorage: Storage = {
  setItem (key, state) {
    // 设置有效期 3 天,不设置默认同 sessionStorage 有效期一致
    return Cookies.set(key, state.accessToken, { expires: 3 }) 
  },
  getItem (key) {
    return JSON.stringify({
      accessToken: Cookies.get(key),
    })
  },
}

export const useUserStore = defineStore('storeUser', {
  state: () => ({
    name: null,
    age: null,
    sex: null,
    accessToken: 'xxxxxxxxx',
  }),
  persist: {
    enabled: true,
    strategies: [
      {
        storage: cookiesStorage, // 使用手动添加的cookie
        paths: ['accessToken'] // cookie 一般用来保存 token
      },
    ],
  },
})