preface

In an era when everyone uses Vue, how can we distinguish between a novice and an experienced vue player? How to let oneself and just learn vUE people open the gap? In fact, many people only use vUE on a basic basis. If you want to improve yourself, you should find a way to apply it to a higher level.


vue

  • component : Global Component Registration
  • Render function : Save the chaotic Template
  • Vue permission control : High precision global access control

1 – “Global Component Registration”

Components are very common, and many people use components to refer to and register them from file to file. This can be especially troublesome if a component is used a lot throughout the project and needs to be referenced and registered for each use

  • General component application disadvantages
    • Stupid. Too clumsy
    • Cumbersome, inefficient
<template>
  <div>
    <h1>I am HelloWorld</h1>
    <Child1></Child1>
  </div>
</template>

<script>
import Child1 from './child1.vue'/ / introductionexport default {
  name: 'HelloWorld'.data() {return{}}, components:{// register Child1}, props: {MSG: String}, methods:{}} </script> <style scoped lang="less">
</style>
Copy the code

When we need to use this component multiple times in a project, it can lead to a lot of repeated introduction and registration code, which can be tedious and unsappy. Therefore, we can manage it through a global Js file, which registers components that need to be used more than once

To create a global.jsFile management global component

// 1 - globalComponent.js

import Vue from 'vue'// Introduce vue // handle the first letter ABC => ABCfunction changeStr(str){
    returnStr.charat (0).toupperCase () + str.slice(1)} /* require.context(arg1,arg2,arg3) arg1 - read the path of the file arg2 - whether to traverse the subdirectory of the file arg3 - */ const requireComponent = require.context(const requireComponent = require.context)'. '.false, /\.vue$/)
console.log('requireComponent.keys():',requireComponent.keys()) // Print requireComponent.keys().foreach (fileName => {const config = requireComponent(fileName) console.log('config:'// print const componentName = changeStr(filename.replace (/^\.\//,' ').replace(/\.\w+$/, ' ') / /. / child1. Vue = > child1) Vue.com ponent (the componentName, config. The default | | config) / / dynamically register all of the directory. The vue file})Copy the code
// 2 - Import GlobalComponent.js to main.js import global from'./components/globalComponent'
Copy the code
<div> <h1>I am HelloWorld</h1> </Child1> </Child1> </div> </template>Copy the code

Run the program, let’s see if we can display and analyze the two sentences

Extra: partitioning routes and dynamically adding routes

Suppose we have a lot of routes, and each route is imported in a silly way, which will increase the amount of code in the whole project and make it tedious. More importantly, it will increase the difficulty of later maintenance. Therefore, you can use the preceding similar methods to manage the import and use of routes. Routes can be imported by partitions. Routes with different functions can be differentiated and dynamically imported, which is convenient and maintainable

Create a dedicated route.jsFile manage all routes
Js - login.routes. Js In a large project, there are often many disconnected modules, such as shopping malls and personal information in the e-commerce platform. In this case, you can partition routesCopy the code

// Partition routing fileexport default {
    path:'/index',
    name:'Index',
    component: () => import('.. /views/Index.vue'), // Introduce the chunk children lazily when the jump occurs: [...] }Copy the code
// 总路由管理文件 index.js 写法
import Vue from 'vue'
import VueRouter from 'vue-router'Use (VueRouter) const routerList = [] // Route array - stores all routesfunctionImportAll (routerArr){// This function is used to add all partitioned routes to the route array. Routerarr.keys ().foreach (key => {console.log(key)) routerList.push(routerArr(key).default) }) } importAll(require.context('. '.true,/\.routes\.js/))

const routes = [
    ...routerList
]

const router = new VueRouter({
    routes
})

export default router
Copy the code

Run the program, let’s see if we can display and analyze the two sentences

Optimized code, will be more flexible, more ornamental, both convenient and efficient, and convenient maintenance


2 – “Save the chaotic Template”

The
tag in the scaffold is often relied upon when writing components.

  • templateThere is one value many judgment in
  • Too much usetemplateIt makes the code redundant and messy

VUE provides us with a render function that subtly resolves the problem caused by the template

Practical – Handle multiple buttons

<template> <div> <h1>I am Home</h1> <! <div v-if= <div v-if= <div v-if='value === 1'>
      <button>button1</button>
    </div>
    <div v-else-if='value === 2'>
      <button>button2</button>
    </div>
    <div v-else>
      <button>button3</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Home'.data() {return{
        value:1
    }
  },
  methods:{
  }
}
</script>

<style scoped lang="less">
</style>
Copy the code

Of course, many people will choose to encapsulate a button component, so the encapsulation of this component, is a skill point, use VUE render function, reduce unnecessary template, so we can write ru like this

// Create a button.vue fileexport default {
    props:{
        type: {type:String,
            default:'normal'
        },
        text:{
            type:String,
            default:'button'}}, render(h){/* h is similar to createElement, taking 2 arguments 1 - element 2 - option */return h('button',{// equivalent to v-bind:class class:{BTN:true.'btn-success':this.type === 'success'.'btn-danger':this.type === 'danger'.'btn-warning':this.type === 'warning'.'btn-normal':this.type === 'normal',
            },
            domProps:{
                innerText: this.text || 'default'
            },
            on:{
                click:this.handleClick
            }
        })
    },
    methods:{
        handleClick(){
            this.$emit('myClick')
        }
    }
}
</script>

<style scoped>
.btn{
    width: 100px;
    height:40px;
    line-height:40px;
    border:0px;
    border-radius:5px;
    color:#ffff;
}
.btn-success{
    background:#2ecc71;
}
.btn-danger{
    background:#e74c3c;
}
.btn-warning{
    background:#f39c12;
}
.btn-normal{
    background:#bdc3c7;
}
</style>
Copy the code
// Introduce <template> <div> <h1>I am Home</h1> <! -- Button displays different types of button based on value --> < buttontype='success' text='button1' @myClick='... '></Button>
  </div>
</template>

<script>
import Button from './button.vue'
export default {
  name: 'Home'.data() {return{
        value:1
    }
  },
  components:{
      Button
  },
  methods:{
  }
}
</script>

<style scoped lang="less">
</style>
Copy the code

In the above writing method, different types of buttons are displayed according to value. We only need to change type, text and so on through value to achieve this purpose, instead of creating multiple

After the optimization of the code, to avoid the value of many judgment shortcomings, reduce redundancy, more flexible, this way is more suitable for simple business, the number of use of components


3 – “High-precision Global Permission handling”

Access control by the front end processing of scenes a lot, such as return content according to the background, and to determine whether a person have permissions to this function to modify elements v – if/v – show, this kind of circumstance, when this function in several places, will cause us to do a lot of a lot of unnecessary repetition code, if the judge conditions complicated situation, more redundant, The amount of code will increase a lot. So we can build a little wheel that hooks globally to handle permissions

Actual – handle a button display permission issue

This scenario is very likely to occur, especially when dealing with projects with multiple roles. If this type of permission judgment is processed multiple times, each time it occurs, the code will be ugly and redundant, so we can handle it with global permission judgment

/* Create a common folder in your project where you can store global.js files. */ // Create a common folder where you can store global.js files. */ // / Create a common folder in your project where you can store global.js filesexport functionCheckJurisdiction (key) {// Permission arraylet jurisdictionList = ['1'.'2'.'3'.'5']
    let index = jurisdictionList.indexOf(key)
    console.log('index:',index)
    if(index > -1) {// Have permissionreturn true
    } else{// No permissionreturn false}}Copy the code
// mount global permission Js to global // main.js import {checklist} from'./common/jurisdiction'// Elegant operation - VUE custom directive VUE. Directive ('permission',{inserted(el, binding){// inserted → When the element is insertedletPermission = binding. Value // Obtain the value of v-permissionif(permission){
      let hasPermission = checkJurisdiction(permission)
      if(! HasPermission) {/ / no permissions remove Dom elements el parentNode && el. ParentNode. RemoveChild (el)}}else{
      throw new Error('Need to pass key')}}})Copy the code
// Use <template> <div> <h1>I am Home</h1> <! -- button based on value --> <div v-permission="' 10 '"> <button> permission 1</button> </div> <div v-permission="' 5 '"</button> </button> </div> </div> </templateCopy the code

Run the program, and let’s see if we can display it and analyze it for printing

v-permission = "'10'"
v-permission = "'5'"


conclusion

The above three aspects seem simple to operate, but many people like to stay in business when writing code and only consider whether it can be realized. In fact, many large projects need these ideas to reduce the amount of code, reduce redundancy, and use the right method in the right scenario to improve their ability

❗ Tips: If there is something wrong in the article, I would like to point it out. If you find it useful, please click “like”