• 在 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) {
        // 删除文件操作
    }

    以上。。

  • 相关阅读:
    最大流最小割——bzoj1001狼抓兔子,洛谷P2598
    求最小公因数和最大公倍数
    归并排序
    Splay
    Tarjan判断为什么不能把dfn写成low
    2-SAT问题
    离散数学-传递闭包(POJ3275)
    POJ3190
    安装环境gcc;
    二分折半排序
  • 原文地址:https://www.cnblogs.com/wenruo/p/11984558.html
Copyright © 2020-2023  润新知