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的語法,轉換成正常的數組格式
