当前位置:网站首页>[boutique] Pinia Persistence Based on the plug-in Pinia plugin persist

[boutique] Pinia Persistence Based on the plug-in Pinia plugin persist

2022-07-06 23:52:00 Liang Yunliang

preparation

First step : install pinia

npm install pinia --save

The second step : newly build store Catalog , establish index.ts

import {
     createPinia } from "pinia"
const store = createPinia()
export default store

The third step :main.ts Use in store

import {
     createApp } from 'vue'
import store from '@/store'

const app = createApp(App)
app.use(store)
app.mount('#app')

Step four : newly build user.ts

import {
     defineStore } from "pinia"

export const useUserStore = defineStore({
    
  id:'user',
  state() {
    
    return {
    
      name: '',
      age: 0
    }
  }
})

Step five : stay vue Page usage

<template>
  User:{
   { name }} == {
   { age }}
  <br>
  <button @click="fun"> Modified value </button>
</template>

<script setup lang="ts"> import {
      useUserStore} from "@/store/module/user" import {
      storeToRefs} from "pinia" const userStore = useUserStore() const {
      name, age} = storeToRefs(userStore) const fun = () => {
       userStore.name = "zhangsan" userStore.age = 18 } </script>

result

Open the page , Click the page button , The displayed user information changes , Refresh the page and return to its original appearance .

Using plug-ins pinia-plugin-persist Persistence

First step : Installing a plug-in pinia-plugin-persist

npm install pinia-plugin-persist --save

The second step : modify store Under folder index.ts

import {
     createPinia } from "pinia"
import piniaPluginPersist from 'pinia-plugin-persist'

const store = createPinia()
store.use(piniaPluginPersist)

export default store

The third step : modify user.ts, To add persist

import {
    defineStore} from "pinia"

export const useUserStore = defineStore({
    
    id: "user",
    state: () => {
    
        return {
    
            name: '',
            age: 0
        }
    },
    persist: {
    
        enabled: true,
        strategies: [
            {
    
                key: 'wego_user',
                storage: localStorage
            }
        ]
    }

})

notes : stay strategies You can specify which data to cache , such as :

strategies: [
    {
     storage: localStorage, paths: ['token','name'] }
]

test

Run the program , Open the page and click the button , Data changes , Close the page and open it again , The page still shows the changed data , here F12, Will see :
 Insert picture description here

原网站

版权声明
本文为[Liang Yunliang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061624454688.html