.eslintrc
在此文件中的选项parserOptions
加入
ecmaFeatures:{
// 支持装饰器
legacyDecorators: true
}
支持了之后就不会报 Parsing error: Stage 2 decorators disallow object literal property decorators
错误
然后就可以愉快的在项目中使用decorator了,不需要额外的安装 @babel/plugin-proposal-decorators
哪些场景可以用装饰器
二次弹窗确认
// xx.vue
<script>
import {confirm} from '@/decorator'
export default {
methods: {
@confirm('确定要删除吗?', '提示')
deleteItem(id) {
deleteItem(id).then(res => {
this.getTableList()
})
}
}
}
</script>
// decorator/index.js
import { $confirm } from 'element-ui'
export function confirm(message, title, cancelFun) {
return (target, name, descriptor) => {
const fn = descriptor.value
descriptor.value = async function(...rest) {
try {
await $confirm({
message,
title
})
fn.apply(this, reset)
} catch(err) {
cancelFun && cancelFun(err)
}
}
}
}