說明
【Vue 開發實戰】學習筆記。
效果
實作兩種方式實作權限元件的控制,比如下面兩個地方的按鈕控制,如果是user使用者,就沒有權限控制
函數式元件
<script>import { check } from '../utils/auth';
export default {
functional: true,
props: {
authority: {
required: true,
type: Array
},
},
render(h,) {
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,) {
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>