一、使用pinia

安装pinia
安装pinia-plugin-persistedstate

vue根目录创建stores,创建indexjs,内容如下:
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'

// app.use(createPinia().use(persist))
const pinia=createPinia()
pinia.use(persist)
export default pinia
export * from './user'
stores文件中再创建user.js,完整代码如下:
import { ref } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios';
import permissions from '@/hook/permissions.json'//所有权限

export const useUserCounter = defineStore('user', () => {
    const userInfo = ref({})
    // 获取用户信息
    const setUserInfo = async () => {
        await axios.get("/api/get_user_information").then(res => {
            if (res.data.code === "1000") {
                userInfo.value = res.data.data
            }
        }, res => {
            console.log('请求失败')
        });
    }
    //清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
        sessionStorage.removeItem('refresh_token')
        sessionStorage.removeItem('Authorization')
    }
    //判断是否有权限
    const hasPermission = (name) =>{
        let flag = false
        let permissionId = null
        permissions.forEach(item =>{
            if(name === item.name){
                permissionId = item.id
            }
        })
        if(permissionId && userInfo.value.permission){
            if(userInfo.value.permission.split(',').indexOf((permissionId.toString())) != -1){
                flag = true
            }
        }
        return flag
    }
    return { userInfo,setUserInfo,clearUserInfo,hasPermission }
}, {
    persist: true //持久化存储
})

其中permissions.json是所有权限的数组列表。

二、登录获取access_token、refresh_token

登录页中先引入user.js
import {useUserCounter} from '@/stores/user'
const userStore = useUserCounter()
登录成功时将接口返回的access_token、refresh_token存入sessionStorage
ElMessage({
    showClose: true,
    message: "登录成功",
    type: "success",
});
setTimeout(function () {
    router.push("/");
    isSubLoadding.value = false;
}, 800);
sessionStorage.setItem('Authorization', res.data.data.access_token)
sessionStorage.setItem('refresh_token', res.data.data.refresh_token)
//获取用户信息
userStore.setUserInfo()
存储token后调用setUserInfo()方法更新userInfo,包含了所有用户信息数据。

三、给axios添加拦截器

在main.js中,引入pinia相关
import pinia from './stores/index'
app.use(pinia)
import { useUserCounter } from '@/stores/user'
const userStore = useUserCounter()
引入axios,设全局
import axios from 'axios'
app.provide('axios', axios)
拦截器完整代码:
// 创建一个 axios 接口
const service = axios.create({
    baseURL: '/api', 
    timeout: 5000, // 请求超时时间设置
    headers: {
        'Authorization': `Bearer ${sessionStorage.getItem('refresh_token')}`
    }
})
service.setToken = (token) => {
    sessionStorage.setItem('Authorization', token)
}
//添加请求拦截器
axios.interceptors.request.use(config => {
    if (sessionStorage.getItem('Authorization')) {
        config.headers.Authorization = `Bearer ${sessionStorage.getItem('Authorization')}`
    }
    return config
}, error => {
    return Promise.reject(error);
})
let isRefreshing = false
// 重试队列,每一项将是一个待执行的函数形式
let requests = []
axios.interceptors.response.use(response => {
    const config = response.config
    if (response.data.code === 401) {
        if (!isRefreshing) {
            isRefreshing = true
            const refresh_token = sessionStorage.getItem('refresh_token')
            if (refresh_token) {
                refreshToken(refresh_token).then(res => {
                    const token = res.data.access_token
                    service.setToken(token)
                    config.headers['Authorization'] = `Bearer ${token}`
                    config.baseURL = ''
                    // 已经刷新了token,将所有队列中的请求进行重试
                    requests.forEach(cb => cb(token))
                    requests = []
                    return service(config)
                }).catch(res => {
                    //获取新token失败,跳转登录页
                    userStore.clearUserInfo()
                    router.push('/login')
                }).finally(() => {
                    isRefreshing = false
                })
            } else {
                userStore.clearUserInfo()
                router.push('/login')
            }
        }
    }
    return response
}, error => {
    return Promise.reject(error);
})
//获取新的token请求
const refreshToken = async (token) => {
    service.defaults.headers['Authorization'] = `Bearer ${token}`
    return service.get('/refresh').then(res => res.data)
}

四、约束操作权限例子

引入user.js
import {useUserCounter} from '@/stores/user'
const userStore = useUserCounter()
获取userinfo
const userinfo = userStore.userInfo
使用方法如下:
<p class="text-right m-b">
   <el-button type="primary" size="small" icon="CirclePlus" @click="createMainPhase" 
   v-if="userStore.hasPermission('添加项目任务')">添加阶段</el-button>
</p>
给方法传对应权限参数,查询userinfo.permission中是否存在该权限,返回true/false。
GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐