Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use decorator in Vue

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to use decorators in Vue". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is a decorator?

Decorator is a new syntax for ES7. Decorator modifies classes, objects, methods, and properties. Add some other behavior to it. In popular terms: it is the secondary packaging of a piece of code.

The use of decorators

It's easy to use. Let's define a function.

Const decorator = (target, name, descriptor) = > {var oldValue = descriptor.value; descriptor.value = function () {alert ('') return oldValue.apply (this,agruments)} return descriptor} / / and then directly @ decorator to the function, class, or object.

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

Js uses decorator / / to 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 } / / Computing class class Calculate {/ / use decorator @ log () function subtraction (AMagol b) {return a-b}} const operate = new Calculate () operate.subtraction (5) do not use decorator 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 (.. func);}} const subtraction = (a, b) = > a + Bten Const subtractionLog = log (subtraction); subtractionLog (10Pol 3)

In this comparison, you will find that the code becomes more readable after using the decorator. The decorator doesn't care about the implementation of your internal 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 don't need to make any configuration to use it. If your project also includes eslit, then you need to enable syntax checking related to supporting decorators in eslit.

/ / add or modify the following code in eslintignore: parserOptions: {ecmaFeatures: {/ / support decorator legacyDecorators: true}}

After adding this code, eslit supports decorator syntax.

Usually in the project, we often use the secondary pop-up box to delete:

/ / decorator.js// assumes that element-uiimport {MessageBox, Message} from 'element-ui'/** * confirmation box * @ param {String} title-title * @ param {String} content-content * @ param {String} confirmButtonText-confirmation button name * @ param {Function} callback-confirmation button name * @ returns * / export function confirm (title, content, confirmButtonText =' OK') {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) ) .catch (error = > {if (error = 'close' | | error = =' cancel') {Message.info ('user cancels the operation')} else {Message.info (error)})} return descriptor}}

As shown above, a MessageBox component in element-ui is executed in the confirm method. When the user cancels, the Message component prompts the user to cancel the operation.

Let's decorate it with decorators on the test () method

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

At this point, the user clicks on a store to delete. The decorator will work. Pop up as shown in the following figure:

When I click cancel:

Tips: the user canceled the operation. The decorated test method is not executed.

When we click OK:

The interface is called and message pops up

Some commonly used decorators

Below, the editor lists several decorators commonly used in the project, which are convenient for everyone to use.

1. Function throttling and anti-shaking

Function throttling and anti-shake application scenarios are relatively wide. Generally, the function to be called is wrapped by throttle or debounce method. Now you can use the above content to encapsulate these two functions into a decorator. Anti-jitter throttling uses the method provided by lodash, and you can also implement the throttling and anti-shake function on your own.

Import {throttle, debounce} from 'lodash'/** * function throttling decorator * @ param {number} wait throttling millisecond * @ param {Object} options throttling option object * [options.leading=true] (boolean): specifies that the call is made before the throttling starts. * [options.trailing=true] (boolean): specifies that the call ends after throttling. * / export const throttle = function (wait, options = {}) {return function (target, name, descriptor) {descriptor.value = throttle (descriptor.value, wait, options)}} / * * function anti-shake decorator * @ param {number} wait the number of milliseconds to delay. * @ param {Object} options option object * [options.leading=false] (boolean): specifies that it is called before the delay begins. * [options.maxWait] (number): sets the maximum allowed delay for func. * [options.trailing=true] (boolean): specifies that it is called after the delay ends. * / export const debounce = function (wait, options = {}) {return function (target, name, descriptor) {descriptor.value = debounce (descriptor.value, wait, options)}}

After encapsulation, use the

Import {debounce} from'@ / decorator'export default {methods: {@ debounce (100) resize () {}} 2. Loading

When loading data, in order to give a friendly prompt to the user and prevent the user from continuing to operate, a loading is usually displayed before the request, and then the loading is turned off after the request ends, which is generally written as follows

Export default {methods: {const loading = Toast.loading () try {const data = await loadData () / other operations} catch (error) {/ / exception handling Toast.fail ('load failed');} finally {loading.clear ()}

We can repackage the above loading logic using a decorator, as follows

Import {Toast} from 'vant'/** * loading decorator * @ param {*} message prompt * @ param {function} errorFn exception handling Logic * / export const loading = function (message =' loading...', errorFn = function () {}) {return function (target, name, descriptor) {const fn = descriptor.value descriptor.value = async function (... rest) {const loading = Toast.loading ({message: message) ForbidClick: true}) try {return await fn.call (this,... rest)} catch (error) {/ / failed in the call And when the user defines the failed callback function, errorFn & & errorFn.call (this, error,... rest) console.error (error)} finally {loading.clear ()} is executed.

Then modify the component code above

Export default {methods: {@ loading ('loading') async getData () {try {const data = await loadData () / other operations} catch (error) {/ / exception handling Toast.fail ('load failed');} 3. Confirmation box

When you click the delete button, you usually need to pop up a prompt box for the user to confirm whether to delete it. At this time, the conventional way of writing may be like this.

Import {Dialog} from 'vant'export default {methods: {deleteData () {Dialog.confirm ({title:' prompt', message: 'make sure you want to delete the data, this operation cannot be reversed. }) .then (() = > {console.log ('delete here')})}}

We can bring up the above confirmation process to make a decorator, as follows

Import {Dialog} from 'vant'/** * confirm prompt box decorator * @ param {*} message prompt * @ param {*} title title * @ param {*} cancelFn cancel callback function * / export function confirm (message =' confirm to delete data, this operation cannot be reversed.' , title = 'prompt', cancelFn = function () {}) {return function (target, name, descriptor) {const originFn = descriptor.value descriptor.value = async function (... rest) {try {await Dialog.confirm ({message, title: title}) originFn.apply (this) Rest)} catch (error) {cancelFn & & cancelFn (error)}

And then when you use the confirmation box, you can use it like this.

Export default {methods: {/ / can not pass parameters. Use the default parameter @ confirm () deleteData () {console.log ('delete here')} "how to use the decorator in Vue". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report