“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

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$/); 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 home from ".. /views/home.vue"; import about from ".. /views/about.vue"; 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/)); // Export default routerList at the end of.module.jsCopy 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]; 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 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, // tag this.$slot.default // subnode array)}, 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.

Import {Button, Select} from 'element-ui'; 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