前端vue:權限控制之權限組件

前言:

涉及到的知識點:vue

arr.includes

/**
  Return boolean
  If the computed index is less or equal than
  (-1 * array.length), the entire array will be searched.
  
  返回值爲boolean 類型,若是查詢字段在數組中存在,則返回true,
  若是查詢字段在數組中不存在,則返回false;
  
  若是 fromIndex <=(-1 * array.length),則從index=0;開始查詢,若是存在則返回true;不然返回false;
  不然返回false;
*/

arr.includes(valueToFind,[fromIndex]); 
複製代碼

函數式組件:

  • 增長渲染性能;
  • 使用靈活方便
  • render(h, context)// params:createElement,context;

Authorized.vue數組

<script>
import { check } from "../utils/auth";  //校驗權限
export default {
  functional: true,
  props: {
    authority: {
      type: Array,
      required: true
    }
  },
  render(h, context) {
    const { props, scopedSlots } = context;
    // 若是校驗經過,則返回子組件/插槽內容;不然返回null;
    return check(props.authority) ? scopedSlots.default() : null;
  }
};
</script>
複製代碼

auth.js

const currentAuth = ["admin"];
export { currentAuth };

export function getCurrentAuthority() {
    return currentAuth;
}

export function check(authority) {
    const current = getCurrentAuthority();
    return current.some(item => authority.includes(item));
}

export function isLogin() {
    const current = getCurrentAuthority();
    return current && current[0] !== "guest";
}
複製代碼

main.js

// 全局註冊組件;

import Authorized from "./components/Authorized";

Vue.component("Authorized", Authorized);
複製代碼

權限組件的使用:

<Authorized :authority="['admin']">
      <SettingDrawer />
    </Authorized>複製代碼
相關文章
相關標籤/搜索