A brief analysis of what is a decorator? How to use decorators in Vue?
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!
# 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
. Decorator
Decorate 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到函数、类或者对象上即可。
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)
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);
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 } }
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 } }
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('操作成功!') } }
At this time, the user clicks on a store to delete it. The decorator will work. The pop-up is as shown below:
When I click cancel:
tips: The user canceled Operation. The modified test method will not execute .
When we click OK:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.
