vue框架中props的typescript用法

时间:2020-12-03 20:07:21

vue框架中props的typescript用法

在vue中使用typescript时,需要引入vue-property-decorator库来兼容格式。

javascript写法

Vue.component('blog-post', {
// 在 JavaScript 中是 camelCase 的
props: ['postTitle'],
template: '<h3>{{ postTitle }}</h3>'
})

typescript写法

  @Prop({
type: Array,
default: function(): Array<LabelData> {
return [];
}
})
label_list: Array<LabelData> | undefined;

typescript和javascript在用法的区别,主要是需要严格规定label_list的类型。

但是,在vue里面,prop是不能赋初始值的。这个规则和typescript会发生矛盾,因此定义类型需要加undefined,避免typescript转义告警。

在代码中使用label_list时,需要用label_list as Array的语法,转换成正常的数组格式

参考链接

vue props

vue-property-decorator