SoFunction
Updated on 2025-04-12

About pinia usage and persistence methods (pinia-plugin-persistedstate)

Pinia-plugin-persistedstate

Install plug-ins

  • npm install pinia
  • npm install pinia-plugin-persistedstate

File configuration

Method 1

  • Initialize configuration in store/file
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

export function setupStore(app) {
  const pinia = createPinia()
  (piniaPluginPersistedstate) //Use persistent storage plug-in  (pinia)
}

export * from './modules/user'
  • Introduce pinia configuration in the entry file
import {
	createSSRApp
} from "vue";
import App from "./";

/** pinia */
import { setupStore } from './store/'

export function createApp() {
	const app = createSSRApp(App);
	setupStore(app); //pinia
	return {
		app,
	};
}

Method 2

  • Configure directly in the file
import { createApp } from 'vue'
import App from './'

// pinia
import { createPinia } from 'pinia'
// Persistence of data in piniaimport { persistedState } from 'pinia-plugin-persistedstate'

// pinia configurationconst pinia=createPinia()
(persistedState)

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

Create pinia module

  • store/modules/

Used on the page

  • state
//

import { defineStore } from "pinia";

/**
  * Parameter 1: Namespace name unique id
  * Parameter 2: {
      state
      Getters
      actions
      persist
  }
  */
 // useUserStore: It is recommended to use use + id + Store to name itexport const useUserStore = defineStore("User", {
  state: () => ({
    userName: "",
    age:18,
    obj:{ money:9999,house:99 },
    hobby:[
        { id: 1, name: 'basketball', level: 1 },
        { id: 2, name: 'rap', level: 10 }
    ]
  }),
  getters: {
    // Similar to the calculation attribute, the parameter state points to the state under defineStore    doubleAge(state) {
      return  * 2;
    },
    // Use another getter in getter to point to the current repository    addOneAge() {
      return  + 1;
    },
    //Return a function    returnFunction(state) {
      return function (id) {
        return ((item) =>  == id);
      };
    },
  },
  //You can access all operations of the entire store instance through this, and support asynchronous operations  actions: {
    //Not asynchronous operation    addAge(e) {
      ("Accepted data", e); //e is the parameter passed by the external call method      //Method 1       =  + e;
      //Method 2      // this.$patch((state) => {
      //    += e;
      // });
    },
    // Simulate asynchronous    asynchronous() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("Simulate asynchronous return value");
        }, 2000);
      });
    },
    // Asynchronous operation    async getList() {
      const res = await ();
      (res);
    },
  },
  persist:true,
});
  • State is similar to data in a component
  • The Store will not be created until it is used, we can use the Store by calling the use function.
  • Once the store is instantiated, you can access any properties defined in state, getters, and actions directly on the store
  • store is an object wrapped with reactive, which means that you don't need to write .value after getter, but, like props in setup, we can't deconstruct it
<template>
  <div class="content">
    <div>My name is{{ userName }},This year{{ age }}age</div>
    <div>Wealth has{{  }}Ten thousand yuan</div>
    <div>Other assets include{{  ||  }}indivual</div>
    <div>Have hobbies</div>
    <div v-for="item in hobby" :key="">
      <div>{{  }}</div>
    </div>
    <button @click="editPiniaHandler">Click to modify</button>
    <button @click="editAll">Click to modify全部</button>
    <button @click="replaceAll">replace</button>
    <button @click="resetBtn">Reset</button>
  </div>
</template>

<script setup>
// import { ref } from 'vue';
import { useUserStore } from '@/store/' //Introduce warehouseimport { storeToRefs } from "pinia"; //Introduce pinia conversion
const userInfoStore = useUserStore()
// const { username, age, like, hobby } = userInfoStore //Direct structure assignment is not responsiveconst { userName, age, hobby, obj } = storeToRefs(userInfoStore); // Responsive
// Modify one by oneconst editPiniaHandler = () => {
   = "Xiao Ming";
   += 1;
};

//Use the $patch method to modify it at one time in the form of an objectconst editAll = () => {
  userInfoStore.$patch({
    userName: "Duck Egg",
    age: 21,
  });
};

// $state replaces state with a new objectconst replaceAll = () => {
  userInfoStore.$state = {
    userName: 'Dog',
    age: '22',
    obj: { money: 10, friend: 1 },
    hobby: [
      { id: 1, name: "football", level: 1 },
      { id: 2, name: "Sing", level: 10 },
    ],
  }
}

// Reset stateconst resetBtn = () => {
  userInfoStore.$reset()
}

</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>

getters

  • Getters is similar to computed properties in components
  • Getters is just a computered property behind the scenes, so no arguments can be passed to them. However, you can return a function from getter to accept any argument
<!-- getterUse -->
<div>take2: {{  }}</div>
<div>Add one: {{  }}</div>
<div>Return a function searchidfor1Hobbies: {{ (1) }}</div>

actions

  • Actions are equivalent to methods in components. They can be useddefineStore()In-houseactionsattribute definition, andThey are great for defining business logic
  • Actions SupportasynchronousOperate, you can write asynchronous functions
<!-- actionUse -->
<button @click="add">Non-asynchronous</button>
<button @click="getList">asynchronous</button>

// Call the method in actionconst add = () => {
  (5)
}
//Calling asynchronous methodconst getList = () => {
  ()
}

Persistence configuration of modules

pinia persistent document official website

/** Persistence usage method 1
  * All data in the current module is persisted
  * Use localStorage for storage
  * By default, id is used as the key in storage
  * Use / for serialization/deserialization
  */
  persist: true, 
  
  
/** Persistence usage method 2
  * key:Storage name
  * storage: storage method
  * path: used to specify which data in the state needs to be persisted. [] means that no state is persisted, undefined or null means that the entire state is persisted.
  */
  persist: {
      key: 'piniaStore', //Storage name      storage: sessionStorage, // Storage method      paths: ['userName','obj'], //Specify stored data  },
  
/** Persistence usage method 3*/
`userName` The value will be saved in `localStorage` middle,
`obj` The value will be saved in `sessionStorage` middle。
`age` Not persisted
 persist:[
    {
       pick:["userName"],
       storage:localStorage
    },
    {
       pick:["obj"],
       storage:sessionStorage
    }
 ],

Using persistent plugins in uniapp

// store/
import { createPinia } from "pinia";
import { createPersistedState } from "pinia-plugin-persistedstate";

export function setupStore(app) {
const pinia = createPinia();
(createPersistUni()); //Use persistent storage plug-in(pinia);
}

/**
 * @description Custom pinia persistence API storage method is uni
 */
// Apply to all modules, if set in a specific module, write to the corresponding modulefunction createPersistUni() {
return createPersistedState({
  storage: {
    getItem: ,
    setItem: ,
  },
});
}

export * from "./modules/user";
// store/moddules/
......
persist: true, // Whether to enable persistence (all data of the current module is persisted)// Configure persistencepersist: {
 pick: ["userName"],
 },

// Configure the persistent storage method of this modulepersist: {
storage: { // Modify storage method getItem: ,
 setItem: 
},
key: 'userInfo', // Local storage of key valuepick: ['', 'age'] // Specify persistent data, do not write default persistence of the entire state}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.