This article has participated in the call for good writing activities, click to view: back end, big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!

preface

Today, we are going to share some of vUE’s advanced combat skills.

skills

Automatic registration component

We might normally introduce a registry component like this. Each time you need to import it in the header, register it, and use it in the template.

<template>
  <div id="app">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App'.components: {
    HelloWorld
  }
}
</script>
Copy the code

So, is there a more convenient and quick way? We might as well.

Create a file called Globalrc.js, which we assume is level with the component, in the component folder.

Directory structure is as follows:

-src
--components
---component1.vue
---globalRC.js

Copy the code

globalRC.js:

import Vue from 'vue'

function changeStr (str){
    return str.charAt(0).toUpperCase() + str.slice(1);
}

const requireComponent = require.context('/'.false./\.vue$/); // the './' operation object is the current directory

requireComponent.keys().forEach(element= > {
    const config = requireComponent(element);

    const componentName = changeStr(
        element.replace(/ ^ \ \ / /.' ').replace(/\.\w+$/.' ')
    )
    
    Vue.component(componentName, config.default || config)
});
Copy the code

Then, we need to import in the main.js file.

import './components/globalRC.js'
Copy the code

Finally, we just need to use it directly in the template.

<template>
  <div id="app">
    <Component1 />
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>
Copy the code

Note that require.context is an API for Webpack, so it needs to be in a Webpack environment to use it.

Automatic route registration

This is the way we registered routes before. If there are many routing files, it will appear particularly bloated.

import Vue from "vue";
import VueRouter from "vue-router";
// Import components
import home from ".. /views/home.vue";
import about from ".. /views/about.vue";
 
// Tell vue to use vueRouter
Vue.use(VueRouter);
 
const routes = [
    {
        path:"/".component: home
    },
    {
        path: "/about".component: about
    }
]
 
var router =  new VueRouter({
    routes
})

export default router;
Copy the code

We can optimize it this way.

Create a routemodule.js file in the routing folder, named router for example.

Directory structure is as follows:

-src
--router
---index.js
---login.module.js
---routeModule.js
Copy the code

routeModule.js:

const routerList = [];

function importAll(r){
    r.keys().forEach(element= > {
        routerList.push(r(element).default);
    });
}

importAll(require.context('/'.true./\.module\.js/));// this is a custom.module.js file
export default routerList

Copy the code

Then, we just need to create the corresponding routing file, such as login.module.js.

export default {
    path:'/login'.name:'login'.component:() = >import('.. /views/login.vue')}Copy the code

Finally, import the routemodule.js file in the route configuration file index.js,


import Vue from "vue";
import VueRouter from "vue-router";
import routerList from './routeModule.js'
 
Vue.use(VueRouter);
  
var router =  new VueRouter({
    routerList
})

export default router;
Copy the code

Note that require.context is an API for Webpack, so it needs to be in a Webpack environment to use it.

Permission custom instruction

Normally, we might encounter the need for button level or in-page permissions, so we can write a global custom directive. First, it can be in the entry file main.js.

import Vue from 'vue'
import App from './App.vue'

function checkArray(key){
    let arr = [1.2.3.4]; // Custom permission list
    let index = arr.indexOf(key);
    if(index>-1) {return true
    }else{
        return false
    }
}

Vue.directive('auth-key', {inserted(el,binding){
    let displayKey = binding.value;
    if(displayKey){
      let hasPermission = checkArray(displayKey);
      if(! hasPermission){ el.parentNode && el.parentNode.removeChild(el); }else{
        throw new Error('need to key')}}}})new Vue({
  render: h= > h(App),
}).$mount('#app')
Copy the code

Use in pages.

<button v-auth-key="8">btn</button> 
Copy the code

Render function

Let’s first look at an example where you’ll see a lot of conditional judgments on templates.

<template>
    <div>
        <h1 v-if="level === 1"></h1>
        <h2 v-else-if="level === 2"></h2>
        <h3 v-else-if="level === 3"></h3>
        <h4 v-else-if="level === 4"></h4>
    </div>
</template>
Copy the code

How do you optimize it? Next, we can use the render function.

Vue.component('anchored-heading', {
  render: function (createElement) {
    return createElement(
      'h' + this.level,   // Label name
      this.$slots.default // Array of child nodes)},props: {
    level: {
      type: Number.required: true}}})Copy the code

Partial introduction of third-party UI framework optimizations

We use the UI framework a lot, and if we use on-demand loading, we need to register to use it every time. Like this:

import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
Use (Button) * vue.use (Select) */

new Vue({
  el: '#app'.render: h= > h(App)
});

Copy the code

We can optimize this by creating a uicompontemps.js file.

// Just add components here each time
import { Button, Select } from 'element-ui';

const components = { Button, Select };

function install(Vue){
    Object.keys(components).forEach(key= > Vue.use(components[key]))
}

export default { install }

Copy the code

It is then imported in the main.js file.

import Vue from 'vue'
import App from './App.vue';

import uIcompontents from "./uIcompontents.js";
Vue.use(uIcompontents);

new Vue({
  el: '#app'.render: h= > h(App)
});
Copy the code

About the author

Author: Vam’s Golden Bean Road. CSDN blog star of the Year 2019, CSDN blog has reached millions of visitors. Nuggets blog post repeatedly pushed to the home page, the total page view has reached hundreds of thousands.

In addition, my public number: front-end experience robbed road, the public continues to update the latest front-end technology and related technical articles. Welcome to pay attention to my public number, let us together in front of the road experience rob it! Go!