In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
小编给大家分享一下Vue中的装饰器如何使用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
相信各位在开发中一定遇到过二次弹框确认相关的需求。不管你使用的是UI框架的二次弹框组件,还是自己封装的弹框组件。都避免不了在多次使用时出现大量重复代码的问题。这些代码的积累导致项目的可读性差。项目的代码质量也变得很差。那么我们如何解决二次弹框代码重复的问题呢?使用装饰器
什么是装饰器?
Decorator是ES7的一个新语法。Decorator通过对类、对象、方法、属性进行修饰。对其添加一些其他的行为。通俗来说:就是对一段代码进行二次包装。
装饰器的使用
使用方法很简单 我们定义一个函数
const decorator = (target, name, descriptor) => { var oldValue = descriptor.value; descriptor.value = function(){ alert('哈哈') return oldValue.apply(this,agruments) } return descriptor}// 然后直接@decorator到函数、类或者对象上即可。
装饰器的目的旨在对代码进行复用。下面我们先来一个小例子看看
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)不使用装饰器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);
这样一对比你会发现使用装饰器后代码的可读性变强了。装饰器并不关心你内部代码的实现。
vue 中使用装饰器
如果你的项目是用vue-cli搭建的 并且vue-cli的版本大于2.5 那么你无需进行任何配置即可使用。如果你的项目还包含eslit 那么你需要在eslit中开启支持装饰器相关的语法检测。【相关推荐:vue.js视频教程】
//在 eslintignore中添加或者修改如下代码:parserOptions: { ecmaFeatures:{ // 支持装饰器 legacyDecorators: true } }
加上这段代码之后eslit就支持装饰器语法了。
通常在项目中我们经常会使用二次弹框进行删除操作:
//decorator.js//假设项目中已经安装了 element-uiimport { 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 }}
如上代码 confirm方法里执行了一个element-ui中的MessageBox组件 当用户取消时 Message组件会提示用户取消了操作。
我们在test()方法上用装饰器修饰一下
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('操作成功!') }}
此时用户点击某个门店进行删除。装饰器将会起作用。弹出如下图所示:
当我点击取消时:
tips: User canceled action. The decorated test method does not execute.
When we click OK:
The interface is called and a message pops up
summary
Decorators are used to wrap a piece of code twice. Add behavior operations and attributes to the code. Using decorators can greatly reduce code duplication. Improve code readability.
The above is "Vue decorator how to use" all the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.