zoukankan      html  css  js  c++  java
  • 在 Vue 中使用 装饰器 Decorator

    Decorator 的语法还没有通过提案,所以项目中很少用。不过最近刚好有一个需求用到了。

    装饰器的语法 http://es6.ruanyifeng.com/#docs/decorator

    需求是,有很多操作都需要二次确认,因为用到的是 element ui 组件,所以就需要在每个函数中都加一个确认操作。

    deleteFile(data) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            type: 'warning'
        }).then(() => {
            // 删除文件操作
        }).catch(() => {});
    }

    每个函数都加一遍。。感觉有点冗余。。于是想到了使用注释器将 confirm 提出去。

    import { MessageBox } from 'element-ui';
    
    function confirmation(target, name, descriptor) {
        let oldValue = descriptor.value;
        descriptor.value = function(...args) {
            MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示')
                .then(oldValue.bind(this, ...args))
                .catch(() => {});
        };
    
        return descriptor;
    }
    @confirmation
    deleteFile(data) {
        // 删除文件操作
    }

    这样只需要在需要二次确认的函数上加一个  @confirmation  即可。

    不过不同的操作需要的提示往往不一样,那就在注释器上加一个参数。

    import { MessageBox } from 'element-ui';
    
    export function confirmation(message) {
        return function(target, name, descriptor) {
            let oldValue = descriptor.value;
            descriptor.value = function(...args) {
                MessageBox.confirm(message, '提示')
                    .then(oldValue.bind(this, ...args))
                    .catch(() => {});
            };
    
            return descriptor;
        }
    }
    @confirmation('此操作将永久删除该文件, 是否继续?')
    deleteFile(data) {
        // 删除文件操作
    }

    以上。。

  • 相关阅读:
    经典的阿里前端笔试题
    Javascript之浏览器兼容EventUtil
    Javascript之对象的创建
    奇妙的CSS之CSS3新特性总结
    前端优化之无阻塞加载脚本
    正则表达式规则与常见的正则表达式
    全端工程师
    最全前端面试问题及答案总结--《转载》
    奇妙的CSS之布局与定位
    关于在django框架里取已登录用户名字的问题
  • 原文地址:https://www.cnblogs.com/wenruo/p/11984558.html
Copyright © 2011-2022 走看看