pinia持久化存储pinia-plugin-persistedstate

2024年05月13日 编程 暂无评论 阅读54 次
[收起]文章目录

介绍

pinia是vue的状态管理库,默认是保存在内存里如果刷新页面状态会丢失。 pinia-plugin-persistedstate插件将pinia状态变化自动保存在localStorage中,这样页面刷新也不会丢失了。官网 https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/

安装

安装:
npm i pinia-plugin-persistedstate

在main.js注册:

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

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

使用

例子一:整个store的所有所有状态都持久化

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => {
    return {
      someState: '你好 pinia',
    }
  },
  persist: true,
})

例子二:store的部分状态持久化

import { defineStore } from 'pinia'  
export const usePiniaTestStore = defineStore('piniaTest', {  
    state: () => {  
        return{  
            testText: "",  
            localText: "",  
        }  
    },  
    persist: {  
        paths: ['localText'],  
    },  
    getters: {  
  
    },  
    actions: {  
  
    },  
})

使用和使用普通pinia状态一样:

<script setup>  
import TwoColumnsResizView from "@/components/BaseComponents/TwoColumnsResizView.vue"  
import {usePiniaTestStore} from "@/store/store.js";  
import {usePiniaLocalTestStore} from "@/store/localstore.js";  
const store = usePiniaTestStore()  
const storeLocal = usePiniaLocalTestStore()  
  
</script>  
  
<template>  
  <TwoColumnsResizView>    
	  <template v-slot:left>  
	      <div>        
		    <p class="text-lg text-rose-500">非持久化:</p>  
	        <el-input  v-model="store.testText" style="width: 240px"/>  
	        <p class="text-purple-700">持久化:</p>  
	        <el-input  v-model="store.localText" style="width: 240px"/>  
	        <p>localstore持久化1:</p>  
	        <el-input  v-model="storeLocal.testText" style="width: 240px"/>  
	        <p>localstore持久化2:</p>  
	        <el-input  v-model="storeLocal.localText" style="width: 240px"/>  
	      </div>    
	  </template>  
      <template v-slot:right>  
	      <div>        
		    <p>非持久化:</p>  
	        <span>{{store.testText}}</span>  
	        <p>持久化:</p>  
	        <span>{{store.localText}}</span>  
	        <p>localstore持久化1:</p>  
	        <span>{{storeLocal.testText}}</span>  
	        <p>localstore持久化2:</p>  
	        <span>{{storeLocal.localText}}</span>  
	      </div>    
      </template>  
   </TwoColumnsResizView>
</template>
<style scoped>  
  
</style>

image-20240513164315833

标签:

给我留言

登录

忘记密码 ?

切换登录

注册