说明
【Vue 开发实战】学习笔记。
效果
实现两种方式实现权限组件的控制,比如下面两个地方的按钮控制,如果是user用户,就没有权限控制
函数式组件
<script> import { check } from '../utils/auth'; export default { functional: true, props: { authority: { required: true, type: Array }, }, render(h, context) { const { props, scopedSlots } = context; return check(props.authority) ? scopedSlots.default() : null; } } </script>
插件方式的指令
import { check } from '../utils/auth'; function install(Vue, options = {}) { Vue.directive(options.name || "auth", { inserted(el, binding) { if(!check(binding.value)) { el.parentNode && el.parentNode.removeChild(el); } } }) } export default {install};
全局注册
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import { Button, Layout, Icon, Drawer, Radio, Menu } from "ant-design-vue"; import Authorized from "./components/Authorized.vue"; import Auth from "./directives/auth"; Vue.config.productionTip = false; Vue.use(Button); Vue.use(Layout); Vue.use(Icon); Vue.use(Drawer); Vue.use(Radio); Vue.use(Menu); Vue.component("Authorized", Authorized); Vue.use(Auth); new Vue({ router, store, render: h => h(App) }).$mount("#app");
使用
<a-icon v-auth="['admin']" class="trigger" :type="collapsed ? 'menu-unfold' : 'menu-fold'" @click="collapsed = !collapsed" ></a-icon> <Authorized :authority="['admin']"> <SettingDrawer /> </Authorized>
组件式相对来说比较灵活,但是需要用的都要嵌套一层。指令的缺点就是如果权限是动态的,就不好处理,具体可以根据业务选择。