话不多说 直接上代码
主要是给h函数设置自定义指令控制
import '@/styles/reset.css'
import '@/styles/global.scss'
import 'uno.css'
import { createApp } from 'vue'
import App from './App.vue'
import { setupRouter } from './router'
import { setupStore } from './store'
import { setupNaiveDiscreteApi } from './utils'
import { setupDirectives } from './directives'
import { permissions } from './globalVariables'
async function bootstrap() {
const app = createApp(App)
// 注册全局变量 添加permissions权限
app.config.globalProperties.$permissions = permissions
setupStore(app)
setupDirectives(app)
await setupRouter(app)
app.mount('#app')
setupNaiveDiscreteApi()
}
bootstrap()
import { router } from '@/router'
const permission = {
mounted(el, binding) {
//拿到当前的route信息
const currentRoute = unref(router.currentRoute)
去取按钮权限集合
const btns = currentRoute.meta?.btns?.map(item => item.code) || []
//判断当前是否存在
if (!btns.includes(binding.value)) {
el.remove()
}
},
}
export function setupDirectives(app) {
//注册自定义指令
app.directive('permission', permission)
}
//resolveDirective 获取当前已经注册过的自定义指令
//withDirectives vue3提供给虚拟dom添加自定义指令的函数
//getCurrentInstance 获取上下文
import { resolveDirective, withDirectives } from 'vue'
// 获取 按钮权限
const permissions = getCurrentInstance()?.appContext.config.globalProperties.$permissions
//获取resolveDirective当前已经注册的指令名 也就是v-xxxx
const permissionDirective = resolveDirective('permission')
{
title: '操作',
key: 'actions',
align: 'center',
width: 100,
fixed: 'right',
render: (row) => {
return [
withDirectives(
h(
NButton,
{
size: 'small',
type: 'primary',
secondary: true,
onClick: () => handleAddOrEdit('edit', row),
},
{ default: () => '修改' },
),
// 添加权限控制
[[permissionDirective, permissions.editNotification]],
),
//交集设置h是否展示
row.xxx === 2 && withDirectives(
h(
NButton,
{
size: 'small',
type: 'error',
style: 'margin-left: 12px;',
secondary: true,
onClick: () => handleDeleteRow(row),
},
{ default: () => '删除' },
),
[[permissionDirective, permissions.delNotification]],
),
]
},
},
针对需要判断状态的时候
把他们放在同一级
row.state !== 2 && withDirectives(
h(
NButton,
{
size: 'small',
type: row.state === 0 ? 'error' : 'warning',
style: 'margin-left: 12px;',
secondary: true,
onClick: () => handlemore('6', row),
},
{ default: () => row.state === 0 ? '冻结' : '解冻' },
),
[[permissionDirective, permissions.frozenUser]],
),