在 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) {
    // 删除文件操作
}
以上。。
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号