装饰器
1. 装饰器
-
Decorator
-
是一种与类相关的语法,用来注释修改类或者类的方法属性,最先执行(普通函数不要使用)
【模板写法】
@ 装饰器
类{
@ 装饰器
类方法{
}
}
装饰器本质上,就是一个函数名!
【普通的类装饰器】
先定义函数名
function test(target){
target.isTestable = true;
}
使用@ 函数名
@ test
class myTest {
}
作用:把类名作为target参数传入,然后给类添加一个新属性isTestable
【含参数的类装饰器】
先定义函数名,是一个闭包,可接受参数,返回一个函数
function test(isTestable){
return function(target){
target.isTestable = isTestable;
}
}
使用@ 函数名
@ test(true)
class myTest {
}
myTest.isTestable //返回true
@ test(false)
class myTest {
}
myTest.isTestable //返回false
【普通的类方法属性装饰器】
先定义上面的函数名,总共有三个参数
对于方法:
target内含构造器,方法,原型
name为方法或者属性名
descriptor为描述符,内含可读性,可枚举性,可配置性的键值
function readonly(target, name, descriptor){
descriptor.writable = false;
return descriptor
}
class Person {
@readonly
abc(){
console.log("...")
}
@readonly
xx = 123
}
2. 在 vue 中的使用
创建项目时,自定义配置加入typescript
以前的引入组件(要在 export default 内)
import { ComponentA, componentB } from "xxx";
export default {
components: { componentA, componentB },
};
新的装饰器引入组件(写在外面即可)
import{ ComponentA, componentB} from 'xxx'
import{ Component } from 'vue-property-decorator'
@Component({
components:{ componentA, componentB }
})
以前的父组件传属性
export default {
props: {
msg: { type: String },
age: { default: "18" },
},
};
新的装饰器的父组件传属性
import{ Component, Vue} from 'vue-property-decorator'
export default class Helloworld extends Vue{
@Prop(String) private msg!:string
@Prop({default:"18"}) private age!:string
}