“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

preface

I believe that you must have encountered in the development of the second frame confirmation related requirements. It doesn’t matter if you’re using the secondary frame component of the UI framework, or if you’re using your own wrapped frame component. You can’t avoid the problem of lots of duplicate code in multiple uses. This accumulation of code makes the project unreadable. The project’s code quality also became poor. So how do we solve the problem of double popbox code duplication? Use decorators

What is a decorator?

Decorator is a new syntax in ES7. Decorators decorate classes, objects, methods, and properties. Add some other behavior to it. In layman’s terms: wrapping a piece of code twice.

The use of decorators

The way to use it is very simple we define a function

const  decorator =  (target, name, descriptor) = > {
 varOldValue = descriptor. The value; descriptor.value =function(){
    alert('ha ha')
    return oldValue.apply(this,agruments)
       }
  return descriptor
}
// Then apply @decorator directly to a function, class, or object.
Copy the code

The purpose of decorators is to reuse code. Let’s start with a small example

Decorators are used in js

// Define a decorator
const log = (target, name, descriptor) = > {
  var oldValue = descriptor.value;
  descriptor.value = function() {
    console.log(`Calling ${name} with`.arguments);
    return oldValue.apply(this.arguments);
  };
  return descriptor;
}
   / / class
  class Calculate {  
 
  // Use decorators
  @log() 
  function  subtraction(a,b){
     return  a - b
   }
 }
 
 const operate  = new Calculate()
  operate.subtraction(5.2)
Copy the code

Don’t use decorators

const log = (func) = > {
  if(typeof(func) ! = ='function') {
    throw new Error(`the param must be a function`);
  }
  return (.arguments) = > {
    console.info(`${func.name} invoke with The ${arguments.join(', ')}`);
    func(...arguments);
  }
}

const subtraction = (a, b) = > a + b;

const subtractionLog = log(subtraction);

subtractionLog(10.3); 

Copy the code

You’ll see that the code is much more readable with decorators. Decorators don’t care about the implementation of your internal code.

Decorators are used in VUE

If your project is built using VUE-CLI and vue-CLI is older than 2.5, you don’t need to do any configuration to use it. If your project also includes Eslit then you need to enable syntax checking for decorator support in Eslit

// Add or modify the following code in eslintignore: parserOptions: {ecmaFeatures:{// Support legacyDecorators: true}}Copy the code

With this code, Eslit supports the decorator syntax.

Usually in a project we use a secondary box to delete:

//decorator.js
// Assume that element-UI is already installed in your project
import { MessageBox, Message } from 'element-ui'
/** * confirmation box *@param {String} title- title *@param {String} content- content *@param {String} confirmButtonText- Confirm the button name *@param {Function} callback- Confirm the button name *@returns* * /
export function confirm(title, content, confirmButtonText = 'sure') {
  return function(target, name, descriptor) {
    const originValue = descriptor.value
    descriptor.value = function(. args) {
      MessageBox.confirm(content, title, {
        dangerouslyUseHTMLString: true.distinguishCancelAndClose: true.confirmButtonText: confirmButtonText
      }).then(originValue.bind(this. args)).catch(error= > {
        if (error === 'close' || error === 'cancel') {
          Message.info('User cancels operation'))}else {
          Message.info(error)
        }
      })
    }
    return descriptor
  }
}
Copy the code

The confirm method performs a MessageBox component of element-UI that prompts the user to cancel when the user cancels.

Let’s decorate the test() method with a decorator

import { confirm } from '@/util/decorator'
import axios form 'axios'
export default {
name:'test'.data(){
return {
  delList: '/merchant/storeList/commitStore'}}},methods:{
 @confirm('Delete store'.'Please confirm whether to delete the store? ')
  test(id){
   const {res,data} = axios.post(this.delList,{id})
   if(res.rspCd + ' '= = ='00000') this.$message.info('Operation successful! ')}}Copy the code

The user then clicks on a store to delete it. Decorators will come into play. Pop up as shown below:

When I hit Cancel:

tips: The user cancels the operation. The modified test method will not execute.

When we click OK:

The interface is called and a message pops up

conclusion

Decorators are used to rewrap a piece of code. Add some behavior actions and attributes to the code. Using decorators can greatly reduce code duplication. Improve code readability.

The last

If the article has the inadequacy place, also invites everybody to criticize to point out.

Thank you for watching this article hope to give a 👍 comment collection three even! Your likes are my motivation to write.