Once and for all component registration

Usually before components are used, you need to import and then register, but if there are many high-frequency components, do this every time, not only a lot of new code, but also low efficiency! How do we optimize?

In fact, we can use webpack’s require.context() method to create our own (module) context to implement automatic dynamic require components.

We first add a file called global.js to the Components folder (which contains high-frequency components), dynamically package all high-frequency components in this file using require.context, and then import the global.js file in the main.js file.

import Vue from 'vue' function changeStr (str) { return str.charAt(0).toUpperCase() + str.slice(1) } const requireComponent = require.context('./', false, /\.vue$/) // Find components that end in vue in the same directory const install = () => {requireComponent.keys().foreach (fileName => {let config = RequireComponent (fileName) console.log(config) //./child1.vue let componentName = changeStr( fileName.replace(/^\.\//, '').replace(/\.\w+$/, '') ) Vue.component(componentName, Config. The default | | config)})} export default {install / / exposed outside the install method}Copy the code

High-precision permission control – Custom directive

We usually add v-if/V-show to an element for permission management, but if the judgment criteria are verbose and multiple places need to be judged, this method of code is not only elegant but also redundant.

In this case, we can handle the global custom directive: we first create a new array.js file, which is used to store permissions related global functions;

export function checkArray (key) { let arr = ['1', '2', '3', '4', 'demo'] let index = arr.indexof (key) if (index > -1) {return true // permission} else {return false // no permission}}Copy the code

Then mount the array file globally:

import { checkArray } from "./common/array";
Vue.directive("permission", {
  inserted (el, binding) {
    let permission = binding.value; // 获取到 v-permission的值
    if (permission) {
      let hasPermission = checkArray(permission);
      if (!hasPermission) { // 没有权限 移除Dom元素
        el.parentNode && el.parentNode.removeChild(el);
      }
    }
  }
});
Copy the code

Finally, we can judge the page through the custom command V-permission:

<button v-permission="'1'"> Permission button 1</button> // will display <button V-permission =" 10 "> Permission button 2</button> // no display <button V - permission = "' demo '" > permissions button 3 < / button > / / displays < / div >Copy the code