当前位置: 首页 > 工具软件 > Persist > 使用案例 >

vue状态管理 pinia pinia-plugin-persist安装使用

夹谷腾
2023-12-01

pinia pinia-plugin-persist安装使用

安装

任意vue项目,我以uniapp为例
官方地址 :pinia github

1初始化package

npm init -y

2安装pinia及持久化工具pinia-plugin-persist

npm i pinia --save
npm i pinia-plugin-persist --save

使用

1项目根目录下创建文件夹pinia-store

pinia-store文件夹名字可以任意起

2在pinia-store下创建文件index.js及模块的js

文件名字可以任意起
index.js

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

login.js

import {
	defineStore
} from 'pinia'
export const useloginStore = defineStore({
	id: 'login', // id必填,且需要唯一
	state: () => {
		return {
			token: '',
			userName: '未登录',
		}
	},
	//开启持久化
	persist: {
		enabled: true,
		// storage:sessionStorage/localStorage,还可以自定义如下
		// https://seb-l.github.io/pinia-plugin-persist/
		// import Cookies from 'js-cookie'
		// const cookiesStorage: Storage = {
		//   setItem (key, state) {
		//     return Cookies.set('accessToken', state.accessToken, { expires: 3 })
		//   },
		//   getItem (key) {
		//     return JSON.stringify({
		//       accessToken: Cookies.getJSON('accessToken'),
		//     })
		//   },
		// }
		strategies: [
		      { storage: localStorage, paths: ['token','userName'] }
		    ],
	},
	// actions 用来修改 state
	actions: {
		login(userName) {
			this.userName = userName
			this.token = "token-" + userName
		},
		logout() {
			this.userName = '已退出登录'
			this.token = ''
			
			
		}
	}
})

3 main.js修改

import App from './App'

// #ifndef VUE3
import Vue from 'vue'

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
	...App,
})
app.$mount()
// #endif

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
// vuex
import store from './store'
// pinia
import pstore from './pinia-store'
//pinia持久化
import piniaPersist from 'pinia-plugin-persist'
export function createApp() {
	const app = createSSRApp(App)
	pstore.use(piniaPersist)
	app.use(pstore)
	app.use(store)
	return {
		app
	}
}
// #endif

4主程序页面

<template>
	<view>
		<view>
			<button type="primary" @click="login('刘大根')">登录</button>
			<button type="default" @click="logout">退出</button>
		</view>
		<!-- <view>{{userName}}</view> -->
		<view>{{loginStore.userName}}</view>
	</view>
</template>

<script>
	// import store from '@/store/index.js'
	// import {
	// 	mapActions,
	// 	mapState
	// } from 'vuex'
import { useloginStore } from '@/pinia-store/login'
const loginStore = useloginStore()

	export default {
		data() {
			return {
				loginStore:loginStore
			}
		},
		computed: {
			// ...mapState(['userName'])			
		},
		methods: {
			// ...mapActions(['login','logout'])
			login(userName){
				loginStore.login(userName)
			},
			logout(){
				loginStore.logout()
			}
		}
	}
</script>
 类似资料: