前端vuepiniapinia-vue存储库
caolibin
[!note]
Pinia是什么?
Pinia 是 ==Vue 的存储库==,它允许您跨组件/页面共享状态
vue项目中有很多页面view,这些view之间相互独立,登录页面会拿到后端传回的token,但是其他页面并没有token,可以将token保存在pinia
,其他页面都可以访问pinia(相当于全局变量),另外pinia基于内存存储,刷新浏览器数据就会丢失,使用persist
插件可以将数据==持久化==
1.安装
用你最喜欢的包管理器安装 pinia
:
yarn add pinia # 或者使用 npm npm install pinia
|
安装pinia持久化插件persist
yarn add pinia-persistedstate-plugin # 或者使用 npm npm install pinia-persistedstate-plugin
|
2.使用
2.1 在main.js
中导入pinia和persist并使用
import {createApp} from 'vue' import App from './App.vue'
import {createPinia} from "pinia"; import {createPersistedState} from "pinia-persistedstate-plugin";
const app = createApp(App)
const pinia = createPinia(); const persist = createPersistedState(); pinia.use(persist);
app.use(pinia);
app.mount('#app')
|
2.2 以保存token为例,创建token.js
文件
import {defineStore} from "pinia"; import {ref} from 'vue';
export const useTokenStore = defineStore('token', () => { const token = ref('') const setToken = (newToken) => { token.value = newToken } const removeToken = () => { token.value = '' } return { token, setToken, removeToken } }, { persis: true } )
|
2.3 在其他页面读取token
import { useTokenStore } from "@/stores/token";
const tokenStore = useTokenStore();
tokenStore.setToken('your token');
console.log("tokenStore:" + tokenStore.token);
tokenStore.removeToken();
|
3.其他示例
reader.js
import {defineStore} from "pinia"; import {ref} from 'vue';
export const useReaderStore = defineStore('reader', () => { const reader = ref({ id: '', username: '', nickname: '', gender: '', age: '', tel: '', token: '' }); const setReader = (data) => { reader.value = data; } const clearReader = () => { reader.value.id = ''; reader.value.username = ''; reader.value.nickname = ''; reader.value.gender = ''; reader.value.age = ''; reader.value.tel = ''; reader.value.token = ''; } return { reader, setReader, clearReader } }, { persis: true } )
|
admin.js
import {defineStore} from "pinia"; import {ref} from 'vue';
export const useAdminStore = defineStore('admin', () => { const admin = ref({ id: '', username: '', nickname: '', token:'' }); let isAdmin = ref(); const setIsAdmin = (flag)=>{ isAdmin.value = flag; } const setAdmin = (data) => { admin.value = data; } const clearAdmin = ()=>{ admin.value.id = ''; admin.value.username = ''; admin.value.nickname = ''; admin.value.token = ''; }
return { admin, setAdmin,isAdmin,setIsAdmin,clearAdmin } }, { persis: true } )
|