Skip to content

Commit 7f17ca6

Browse files
authored
docs: add a guide to annotate component type in decorator (#450)
1 parent a9739d2 commit 7f17ca6

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

Diff for: docs/.vuepress/config.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ module.exports = {
4444
'guide/props-definition.md',
4545
'guide/property-type-declaration.md',
4646
'guide/refs-type-extension.md',
47-
'guide/hooks-auto-complete.md'
47+
'guide/hooks-auto-complete.md',
48+
'guide/annotate-component-type-in-decorator'
4849
]
4950
}
5051
]

Diff for: docs/guide/annotate-component-type-in-decorator.md

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Annotate Component Type in Decorator
2+
3+
There are cases that you want to use your component type on a function in `@Component` decorator argument.
4+
For example, to access component methods in a watch handler:
5+
6+
```ts
7+
@Component({
8+
watch: {
9+
postId(id: string) {
10+
// To fetch post data when the id is changed.
11+
this.fetchPost(id) // -> Property 'fetchPost' does not exist on type 'Vue'.
12+
}
13+
}
14+
})
15+
class Post extends Vue {
16+
postId: string
17+
18+
fetchPost(postId: string): Promise<void> {
19+
// ...
20+
}
21+
}
22+
```
23+
24+
The above code produces a type error that indicates `fetchPost` does not exist on `this` in the watch handler. This happens because `this` type in `@Component` decorator argument is the base `Vue` type.
25+
26+
To use your own component type (in this case `Post`), you can annotate the decorator through its type parameter.
27+
28+
```ts
29+
// Annotate the decorator with the component type 'Post' so that `this` type in
30+
// the decorator argument becomes 'Post'.
31+
@Component<Post>({
32+
watch: {
33+
postId(id: string) {
34+
this.fetchPost(id) // -> No errors
35+
}
36+
}
37+
})
38+
class Post extends Vue {
39+
postId: string
40+
41+
fetchPost(postId: string): Promise<void> {
42+
// ...
43+
}
44+
}
45+
```

0 commit comments

Comments
 (0)