From e4d31a091ccc1c170b1af0f22bf3104330d9e2c7 Mon Sep 17 00:00:00 2001 From: ktsn Date: Mon, 14 Sep 2020 23:46:47 +0800 Subject: [PATCH] docs: add a guide to annotate component type in decorator --- docs/.vuepress/config.js | 3 +- .../annotate-component-type-in-decorator.md | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 docs/guide/annotate-component-type-in-decorator.md diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 552507b..a316ebb 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -44,7 +44,8 @@ module.exports = { 'guide/props-definition.md', 'guide/property-type-declaration.md', 'guide/refs-type-extension.md', - 'guide/hooks-auto-complete.md' + 'guide/hooks-auto-complete.md', + 'guide/annotate-component-type-in-decorator' ] } ] diff --git a/docs/guide/annotate-component-type-in-decorator.md b/docs/guide/annotate-component-type-in-decorator.md new file mode 100644 index 0000000..cb3412d --- /dev/null +++ b/docs/guide/annotate-component-type-in-decorator.md @@ -0,0 +1,45 @@ +# Annotate Component Type in Decorator + +There are cases that you want to use your component type on a function in `@Component` decorator argument. +For example, to access component methods in a watch handler: + +```ts +@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 { + // ... + } +} +``` + +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. + +To use your own component type (in this case `Post`), you can annotate the decorator through its type parameter. + +```ts +// Annotate the decorator with the component type 'Post' so that `this` type in +// the decorator argument becomes 'Post'. +@Component({ + watch: { + postId(id: string) { + this.fetchPost(id) // -> No errors + } + } +}) +class Post extends Vue { + postId: string + + fetchPost(postId: string): Promise { + // ... + } +} +```