发布时间:2023-04-22 文章分类:WEB开发, 电脑百科 投稿人:王小丽 字号: 默认 | | 超大 打印

文章目录

    • 1 前言
    • 2 持久化存储
      • 2.1 安装依赖
      • 2.2 新增 store 文件
      • 2.3 修改 main.ts 文件
      • 2.4 持久化存储测试
    • 3 高级配置
      • 3.1 存储所有变量
      • 3.2 存储部分变量

1 前言

2 持久化存储

2.1 安装依赖

pnpm i pinia // 安装 pinia
pnpm i pinia-plugin-persist // 安装持久化存储插件

2.2 新增 store 文件

import type { App } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export function setupStore(app: App<Element>) {
  app.use(store)
}
export { store }

2.3 修改 main.ts 文件

import { createApp } from 'vue'
import App from './App.vue'
import { setupStore } from './store'
import router from './router/routes'
const app = createApp(App)
setupStore(app)
app.use(router).mount('#app')

2.4 持久化存储测试

import { defineStore } from 'pinia'
const userStore = defineStore('user', {
  state: () => {
    return {
      accessToken: '',
      userName: ''
    }
  },
  actions: {
    SET_ACCESS_TOKEN(token: string) {
      this.accessToken = token
    },
    SET_USER_NAME(name: string) {
      this.userName = name
    }
  },
  persist: {
    enabled: true,
  }
})
export default userStore

若不生效,需检查全局是否注册多个 Pinia (全局搜索createPinia

比如 main.ts 文件重新注册了 Pinia

import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import router from './router/routes'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.use(router).mount('#app')

3 高级配置

3.1 存储所有变量

默认存储到 sessionStorage ,key 为 store 的 id

persist: {
  enabled: true
}

存储到 localStorage ,key 为 store 的 id

persist: {
  enabled: true,
  strategies: [
    {
      storage: localStorage,
    },
  ]
}

自定义存储 key 值

persist: {
  enabled: true,
  strategies: [
    {
      key: 'piniaStore',
      storage: localStorage,
    },
  ]
}

3.2 存储部分变量

默认存储到 sessionStorage

persist: {
  enabled: true,
  strategies: [
    {
      paths: ['accessToken']
    },
  ]
}

自定义存储到 localStorage

persist: {
  enabled: true,
  strategies: [
    {
      storage: localStorage,
      paths: ['accessToken']
    },
  ]
}

自定义存储到 sessionStorage 和 localStorage

persist: {
  enabled: true,
  strategies: [
    { storage: sessionStorage, paths: ['userName'] },
    { storage: localStorage, paths: ['accessToken'] }
  ]
}