Home > Web Front-end > Vue.js > A brief analysis of what is a decorator? How to use decorators in Vue?

A brief analysis of what is a decorator? How to use decorators in Vue?

青灯夜游
Release: 2022-01-26 18:06:42
forward
2909 people have browsed it

What is a decorator? This article will introduce you to decorators and briefly introduce how to use decorators in js and vue. I hope it will be helpful to you!

A brief analysis of what is a decorator? How to use decorators in Vue?

# I believe that you must have encountered the need for secondary pop-up confirmation during development. Whether you are using the secondary pop-up component of the UI framework or your own encapsulated pop-up component. All of them cannot avoid the problem of a large amount of repeated code when used multiple times. The accumulation of these codes results in poor readability of the project. The code quality of the project has also become very poor. So how do we solve the problem of duplicate pop-up codes? Using Decorators

What are decorators?

Decorator is a new syntax for ES7. DecoratorDecorate classes, objects, methods, and properties. Add some additional behavior to it. In layman's terms: it is a secondary packaging of a piece of code.

The use of decorators

The method of use is very simple. We define a function

const  decorator =  (target, name, descriptor) => {
 var oldValue = descriptor.value;
 descriptor.value = function(){
    alert('哈哈')
    return oldValue.apply(this,agruments)
       }
  return descriptor
}
// 然后直接@decorator到函数、类或者对象上即可。
Copy after login

The purpose of the decorator is to reuse the code. Let's take a small example first to see

Using decorators in js

//定义一个装饰器 
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 Calculate {  
 
  //使用装饰器
  @log() 
  function  subtraction(a,b){
     return  a - b
   }
 }
 
 const operate  = new Calculate()
  operate.subtraction(5,2)
Copy after login

Not using 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 ${arguments.join(',')}`);
    func(...arguments);
  }
}

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

const subtractionLog = log(subtraction);

subtractionLog(10,3);
Copy after login

In this comparison, you will find that the code after using decorators Readability has become stronger. Decorators don't care about the implementation of your inner code.

Using decorators in vue

If your project is built with vue-cli and the version of vue-cli is greater than 2.5, you can use it without any configuration. If your project also contains eslit, then you need to enable support for decorator-related syntax detection in eslit. [Related recommendations: vue.js video tutorial]

//在 eslintignore中添加或者修改如下代码:
parserOptions: {
    ecmaFeatures:{
      // 支持装饰器
      legacyDecorators: true
    }
  }
Copy after login

After adding this code, eslit will support decorator syntax.

Usually in projects, we often use secondary pop-up boxes for deletion operations:

//decorator.js
//假设项目中已经安装了 element-ui
import { MessageBox, Message } from 'element-ui'
/**
 * 确认框
 * @param {String} title - 标题
 * @param {String} content - 内容
 * @param {String} confirmButtonText - 确认按钮名称
 * @param {Function} callback - 确认按钮名称
 * @returns
   **/
export function confirm(title, content, confirmButtonText = '确定') {
  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('用户取消操作'))
        } else {
          Message.info(error)
        }
      })
    }
    return descriptor
  }
}
Copy after login

The above code confirm method executes a MessageBox component in element-ui When the user cancels, the Message component will prompt the user to cancel the operation.

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('删除门店','请确认是否删除门店?')
  test(id){
   const {res,data} = axios.post(this.delList,{id})
   if(res.rspCd + '' === '00000') this.$message.info('操作成功!')
  }
}
Copy after login

At this time, the user clicks on a store to delete it. The decorator will work. The pop-up is as shown below:

A brief analysis of what is a decorator? How to use decorators in Vue?

When I click cancel:

A brief analysis of what is a decorator? How to use decorators in Vue?

tips: The user canceled Operation. The modified test method will not execute .

When we click OK:

A brief analysis of what is a decorator? How to use decorators in Vue?

The interface is called and the message pops up

Summary

The decorator is used To repackage a piece of code. Add some behavioral operations and attributes to the code. Using decorators can greatly reduce code duplication. Improve code readability.

Finally

If there are any shortcomings in the article, please criticize and point it out.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of A brief analysis of what is a decorator? How to use decorators in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template