vue3 自定义指令以插件的形式全局注册实现按钮权限

第一步:新建directive文件夹包含想要自定义指令的文件,

hasPermission.js是用户人员权限  hasRolePermission.js是角色权限

hasPermission.js内容如下:

import useUserStore from '@/store/modules/user.ts'
const userStore:any = useUserStore()
const hasPermission = {
    mounted(el:any, binding:any){
        if(!binding.value.includes(userStore.userId*1)){
            el.parentNode.removeChild(el)
        }
    }
}

export default hasPermission

hasRolePermission内容如下:

import usePermissionStore from '@/store/modules/permission.ts'
const usePermission:any = usePermissionStore()
const hasRolePermission = {
    mounted(el:any, binding:any){
        if(usePermission.allButtons?.length){
            if(!usePermission.allButtons.some((btn:any)=>btn.permits === binding.value)){
                el.parentNode.removeChild(el)
            }else{
                //如果有权限则设置内容为后端返回的内容
                el.textContent = usePermission.allButtons.find((btn:any)=>btn.permits === binding.value)?.menuName
            }
        }
    }
}

export default hasRolePermission

 新建plugins文件夹,编写一个自动注册全局指令的插件

plugins/index.js

import hasPermission from './userHasPermission.ts'
import hasRolePermission from './hasRolePermission.ts'
const directives:any = {
    hasPermission,
    hasRolePermission
} 

export default {
    install(app:any) {
      Object.keys(directives).forEach((key) => {
        app.directive(key, directives[key])
      })
    },
}

在main.js中引入使用使用编写的插件:

import directive from '@/plugins/index.ts'
const app = createApp(App);
app.use(directive)

周后使用任意页面组件中使用

<template #option="{row, index}">
                <el-button v-hasPermission="[2,3,4,5,6]" v-if="permitsButton('system:inventoryCount:confirm')" link
                       type="primary" @click="confirmSh({id:row['id']})">
                  {
   
   { permitsButton("system:inventoryCount:confirm") }}
                </el-button>
                <el-button v-hasRolePermission="'system:inventoryCount:edit'" icon="Edit" link
                       type="primary" @click="addorEditRef?.open(row,1)">
                </el-button>
              </template>

pinia内容截图好理解:

扫描二维码关注公众号,回复: 17157731 查看本文章

猜你喜欢

转载自blog.csdn.net/Lsir1998/article/details/134728899