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) {
// 刪除文件操作
}
以上。。
