Skip to content

Commit 506247b

Browse files
authored
feat: add lifecycle types into vue instance type (#371)
* fix: add lifecycle types into vue instance type * docs: state about to add lifecycle hook type
1 parent 2fc6ab5 commit 506247b

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

Diff for: README.md

+31
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,37 @@ new Vue({
200200
})
201201
```
202202

203+
In TypeScript, all built-in lifecycle hools and special methods are declared in the component instance type to enable auto-complete in editors.
204+
If you want to make it work with custom hooks, you can manually add it by yourself:
205+
206+
```ts
207+
import Vue from 'vue'
208+
import { Route, RawLocation } from 'vue-router'
209+
210+
declare module 'vue/types/vue' {
211+
// Augment component instance type
212+
interface Vue {
213+
beforeRouteEnter?(
214+
to: Route,
215+
from: Route,
216+
next: (to?: RawLocation | false | ((vm: V) => any) | void) => void
217+
): void
218+
219+
beforeRouteLeave?(
220+
to: Route,
221+
from: Route,
222+
next: (to?: RawLocation | false | ((vm: V) => any) | void) => void
223+
): void
224+
225+
beforeRouteUpdate?(
226+
to: Route,
227+
from: Route,
228+
next: (to?: RawLocation | false | ((vm: V) => any) | void) => void
229+
): void
230+
}
231+
}
232+
```
233+
203234
### Caveats of Class Properties
204235

205236
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.

Diff for: src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import './lifecycle'
12
import Vue, { ComponentOptions } from 'vue'
23
import { VueClass } from './declarations'
34
import { componentFactory, $internalHooks } from './component'

Diff for: src/lifecycle.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { VNode } from 'vue'
2+
3+
declare module 'vue/types/vue' {
4+
interface Vue {
5+
data?(): object
6+
beforeCreate?(): void
7+
created?(): void
8+
beforeMount?(): void
9+
mounted?(): void
10+
beforeDestroy?(): void
11+
destroyed?(): void
12+
beforeUpdate?(): void
13+
updated?(): void
14+
activated?(): void
15+
deactivated?(): void
16+
render?(createElement: CreateElement): VNode
17+
errorCaptured?(err: Error, vm: Vue, info: string): boolean | undefined
18+
serverPrefetch?(): Promise<unknown>
19+
}
20+
}

0 commit comments

Comments
 (0)