vue3 pinia持久化插件使用

pinia官网

首选安装pinia

npm install pinia
// 或者
yarn add pinia

安装pinia的持久化插件

npm install pinia-plugin-persist --save

在vue 入口文件main.js中

import { createPinia } from 'pinia' 
import piniaPersist from 'pinia-plugin-persist' // 引入pinia 持久化插件
const pinia = cratePinia() // 创建pinia实例
pinia.use(piniaPersist)

在store下创建counter.js

import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
	state: () => {
		return {
			count: 1
			name: 'counter'
		}
	},
	getters: {
		double: (state) => state.count*2
	},
	actions: {
		increment: () => {
			this.count++
		},
		changName: (payload) => {
			this.name = payload
		}
	},
	// 使用持久化插件
	// persist: true // 开启持久化存储,不配置选项
	// 或者配置持久化
	persist: {
		enabled: true,
		strategies: [
		    { storage: sessionStorage, paths: ['count', 'name'] }, // count,name存储在sessionStorage
		    { storage: localStorage, paths: ['token']}
    	]
	}
})

你可能感兴趣的:(Vue,vue.js)