首页 > 其他分享 >VUE动态路由和按钮的实现

VUE动态路由和按钮的实现

时间:2024-08-03 08:56:30浏览次数:8  
标签:VUE const route next 按钮 权限 路由

动态路由

动态菜单

//通过循环组件完成动态菜单
 <el-menu active-text-color="#ffd04b" background-color="#545c64" class="el-menu-vertical-demo" text-color="#fff"
        :collapse="isCollapse" router default-active style="width: auto;">
        <el-menu-item index="99">
            <img src="@/assets/logo.svg" width="18" />
            <span style="font-weight: bold;">TMS用户管理系统</span>
        </el-menu-item>
        <el-menu-item index="/Main">
            <el-icon>
                <HomeFilled />
            </el-icon>
            <span>首页</span>
        </el-menu-item>
        <RecursiveMenuItem :apidto="apidto" />
        <el-menu-item
            @click="isCollapse = !isCollapse; isCollapse == true ? iconSwitch = 'Expand' : iconSwitch = 'Fold'">
            <el-icon style="font-size: 20px;">
                <component :is="iconSwitch"></component>
            </el-icon>
            <span>展开</span>
        </el-menu-item>
    </el-menu>
//子组件
 <template v-for="item in props.apidto" key="item">
        <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.mName" :key="item">
            <template #title>
                <el-icon>
                    <component :is="item.mIcol" />
                </el-icon>
                <span>{{ item.mName }}</span>
            </template>
            <RecursiveMenuItem :apidto="item.children" /> <!-- 递归调用自身 -->
        </el-sub-menu>
        <el-menu-item v-else :index="item.roUrl">
            <el-icon>
                <component :is="item.mIcol" />
            </el-icon>
            <span>{{ item.mName }}</span>
        </el-menu-item>
    </template>

动态路由

import router from '@/router/index'
const modules = import.meta.glob('../views/**/*.vue')
//导航守卫+动态路由
//to是要跳转到的页面
//form是跳转前的页面
//next是不做任何阻拦允许跳转
router.beforeEach((to, from, next) => {
    //pinia中获取用户登录状态
    const CounterStore = useCounterStore();
    //是否为登录状态,并且令牌不为空
    if (CounterStore.isLogin && localStorage.getItem('token')) {
        //如果路由是登录页面则跳转到主页
        if (to.path === '/') {
            next({
                path: '/Main'
            })
        }
        //不为登录页面
        else {
            //如果路由不存在则添加路由
            if (to.name === undefined) {
                const routes = JSON.parse(localStorage.getItem('apidto') as string);
                addRoutesRecursively(routes);
                next({ ...to, replace: true })
            }
            next();
        }
    }
    //如果没有登录
    else {
        if (to.path === '/') {
            next()
        }
        else {
            next({
                path: '/'
            })
        }
    }
})
//递归获取用户
function addRoutesRecursively(routes: any[]) {
    routes.forEach((route) => {
        // 假设 route 可能包含 children 属性  
        if (route.children) {
            // 递归调用自身来处理 children  
            addRoutesRecursively(route.children);
        }
        // 添加当前路由
        else {
            router.addRoute('Main', {
                path: route.roUrl,
                name: route.roName,
                component: modules['../views' + route.moUrl] // 注意这里可能需要根据实际情况调整路径拼接方式  
            });
        }
    });
}

动态按钮

//pinia状态管理	
import { useUserStore } from '../stores/User'
import type { Directive, DirectiveBinding } from "vue";

//权限按钮自定义事件

export const hasPerm: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        // DOM绑定需要的按钮权限标识
        const { value: requiredPerms } = binding;
        if (requiredPerms) {
            if (!hasAuth(requiredPerms)) {
                el.parentNode && el.parentNode.removeChild(el);
            }
        } else {
            throw new Error(
                "你没有权限"
            );
        }
    },
};

// 是否有权限
function hasAuth(
    value: string | string[],
    type: "button" | "role" = "button"//约束type只能为button或role,同时赋值默认值button
) {
    //获取账号下的角色和权限
    const userStore = useUserStore();
    const { roles, perms } = userStore.users;
    //「终极管理员」拥有所有的按钮权限
    if (type === "button" && roles.includes("终极管理员")) {
        return true;
    }
    //判断是否获取的是按钮权限,否则获取角色权限
    const auths = type === "button" ? perms : roles;
    //判断用户value是一堆角色还是单个角色
    return typeof value === "string"
        ? auths.includes(value)//判断用户是否有这个权限
        : auths.some((perm) => {
            return value.includes(perm);//查询需要的权限是否拥有,可能是一个按钮可以有好几个角色访问
        });
}

//Main中注册
//注册全局自定义指令
app.directive("hasPerm", hasPerm);


标签:VUE,const,route,next,按钮,权限,路由
From: https://www.cnblogs.com/zhaoshiyi/p/18340011

相关文章

  • 使用SpringBoot+Vue3来实现前后端登录注册功能(新手入门,带你一步一步实现)
    目录一.所用技术栈:二.前端创建工程: 1.使用elementplus展开前端页面格式布局:2.基于Vue3的使用来实现登录与注册:(1)定义数据模型:(2):model绑定表单:(3)表单数据校验:①定义表单校验规则:②给表单绑定校验规则:(4)前端注册功能开发: ①创建request.js请求工具:②创建user.js来调用......
  • 如何更改 python-prompt-toolkit 中聚焦按钮的颜色
    我正在使用python-prompt-toolkit在Python中构建一个音乐播放器。我想改变聚焦按钮的颜色,但我不太明白。为了实现这一点,我尝试查看buttons.py.在其GitHub上给出的示例中,给出的颜色是红色,但是当我将其更改为绿色时,它不会改变,即保持红色。任何帮助,将不胜感激。......
  • Vue 使用 vue-drag-resize 实现拖拽和随意缩放大小及安装报错处理
    一、vue-drag-resize的安装yarnaddvue-drag-resize 下面是错误解决方案:TypeError:Cannotreadpropertiesofundefined(reading‘_c’) 解决方案:在引入时加上“/src”: importVueDragResizefrom"vue-drag-resize";改成importVueDragResizefrom"vue-d......
  • uniapp 路由uni.navigateTo 传参
    1.传递一个参数 letindex=1;uni.navigateTo({url:`../address/address?key=${index}`})接收一个参数onLoad(e){console.log(e.index)}2.传递两个参数letnamename="loadVessel"letidid="1"uni.navigateTo({url:`......
  • springboot+vue前后端分离项目-项目搭建15-集成JWT token权限验证
    1.对之前的代码改造,之前将user存储到sessionStorage,改成存储到localStorage,全局搜索修改 之前Result.code等于0代表success,改成200代表success,vue文件全局搜索修改一、前端部分1.改造request.js,登录时将user已经存储到localStorage里,这里将user获取到,将user里的token放到......
  • vue3统一封装axios
    1.在src下新建文件夹apis在apis下新建一个index.ts2.在index.ts添加importaxiosfrom'axios';exportconsthttpInstance=axios.create();3.在终端输入npmrunlint确定文件没有问题4.定义并导出一个后端的数据类型exporttypeBkResponse={data:any;code:numb......
  • vue同时校验多个表单
    最开始的想法是将两个表单绑定同一个ref,这样在调用ref.value.validate()是否可以同时校验两个表单呢?(1)修改两个表单同时绑定formARef,点击按钮进行校验:只有第二个表单进行校验了,这是因为在Vue3中,使用ref绑定表单元素时,如果你给两个不同的表单元素都绑定了相同的ref,例如re......
  • vue使用Element-plus创建个性按钮
    npminstallelement-plus--save下载element-plus2.npminstall-Dunplugin-vue-componentsunplugin-auto-import导入方式:自动导入不需要安装插件3.配置文件将:importAutoImportfrom'unplugin-auto-import/vite'importComponentsfrom'unplugin-vue-components/vi......
  • Vue3+elementplus遇到的常见问题
    1.跳转同一个路由的时候,只是参数不一样页面不刷新,不会执行onMounted尝试多种方案,包括watch等最终解决方案:router-view设置key属性为路由的完整路径<keep-alive><router-view:key="$route.fullPath"></router-view></keep-alive>eg:左侧菜单是接口返回的  默......
  • 基于springboot+vue.js+uniapp在线考试系统的附带文章源码部署视频讲解等
    在这里插入图片描述@toc前言......