From 94b34e5c4ecac00747bf464980f529adcf08bd13 Mon Sep 17 00:00:00 2001 From: ktsn Date: Mon, 11 Nov 2019 23:51:11 +0800 Subject: [PATCH 1/2] fix: add lifecycle types into vue instance type --- src/index.ts | 1 + src/lifecycle.ts | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 src/lifecycle.ts diff --git a/src/index.ts b/src/index.ts index d2b955b..837e326 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ +import './lifecycle' import Vue, { ComponentOptions } from 'vue' import { VueClass } from './declarations' import { componentFactory, $internalHooks } from './component' diff --git a/src/lifecycle.ts b/src/lifecycle.ts new file mode 100644 index 0000000..afc0986 --- /dev/null +++ b/src/lifecycle.ts @@ -0,0 +1,20 @@ +import { VNode } from 'vue' + +declare module 'vue/types/vue' { + interface Vue { + data?(): object + beforeCreate?(): void + created?(): void + beforeMount?(): void + mounted?(): void + beforeDestroy?(): void + destroyed?(): void + beforeUpdate?(): void + updated?(): void + activated?(): void + deactivated?(): void + render?(createElement: CreateElement): VNode + errorCaptured?(err: Error, vm: Vue, info: string): boolean | undefined + serverPrefetch?(): Promise + } +} From 9fc35a16db324e0f4b40668ae2be3386fbcbecea Mon Sep 17 00:00:00 2001 From: ktsn Date: Tue, 12 Nov 2019 00:04:10 +0800 Subject: [PATCH 2/2] docs: state about to add lifecycle hook type --- README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/README.md b/README.md index de79e04..71bcb66 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,37 @@ new Vue({ }) ``` +In TypeScript, all built-in lifecycle hools and special methods are declared in the component instance type to enable auto-complete in editors. +If you want to make it work with custom hooks, you can manually add it by yourself: + +```ts +import Vue from 'vue' +import { Route, RawLocation } from 'vue-router' + +declare module 'vue/types/vue' { + // Augment component instance type + interface Vue { + beforeRouteEnter?( + to: Route, + from: Route, + next: (to?: RawLocation | false | ((vm: V) => any) | void) => void + ): void + + beforeRouteLeave?( + to: Route, + from: Route, + next: (to?: RawLocation | false | ((vm: V) => any) | void) => void + ): void + + beforeRouteUpdate?( + to: Route, + from: Route, + next: (to?: RawLocation | false | ((vm: V) => any) | void) => void + ): void + } +} +``` + ### Caveats of Class Properties vue-class-component collects class properties as Vue instance data by instantiating the original constructor under the hood. While we can define instance data like native class manner, we sometimes need to know how it works.