# 在装饰器中标注组件类型
在某些情况下,您可能希望在 @Component
装饰器参数中使用您的组件类型。例如,在 watch 处理程序中访问组件方法
@Component({
watch: {
postId(id: string) {
// To fetch post data when the id is changed.
this.fetchPost(id) // -> Property 'fetchPost' does not exist on type 'Vue'.
}
}
})
class Post extends Vue {
postId: string
fetchPost(postId: string): Promise<void> {
// ...
}
}
上面的代码会产生一个类型错误,表明 fetchPost
在 watch 处理程序中的 this
上不存在。这是因为 @Component
装饰器参数中的 this
类型是基础 Vue
类型。
要使用您自己的组件类型(在本例中为 Post
),您可以通过其类型参数来标注装饰器。
// Annotate the decorator with the component type 'Post' so that `this` type in
// the decorator argument becomes 'Post'.
@Component<Post>({
watch: {
postId(id: string) {
this.fetchPost(id) // -> No errors
}
}
})
class Post extends Vue {
postId: string
fetchPost(postId: string): Promise<void> {
// ...
}
}
← 钩子自动完成