描述
App.vue
<script setup lang="ts">
import { provide, ref, nextTick } from 'vue'
const isRouterAlive = ref<boolean>(true)
const reload = () => {
isRouterAlive.value = false
nextTick(() => {
isRouterAlive.value = true
})
}
provide('reload', reload)
</script>
OtherComponent.vue
<script setup lang="ts">
import { reactive, inject } from 'vue'
const reload = inject('reload')
const fun1 = () => {
reload()
}
</script>
此时TS会报错:'reload' is of type 'unknown'.
解决方案
判断类型
if (typeof reload === 'function') {
reload()
}
给定初始值
const reload = inject('reload', () => {})
const reload = inject('reload') as () => {}
3. InjectionKey
function provide<T>(key: InjectionKey<T> | string | number, value: T): void
function inject<T>(key: InjectionKey<T> | string): T | undefined
function inject<T>(key: InjectionKey<T> | string, defaultValue: T, treatDefaultAsFactory?: false): T
function inject<T>(key: InjectionKey<T> | string, defaultValue: T | (() => T), treatDefaultAsFactory: true): T
types.ts
import type { InjectionKey } from 'vue'
export const reloadInjectKey: InjectionKey<() => {}> = Symbol('reload')
App.vue
import { reloadInjectKey } from '@/utils/types'
provide(reloadInjectKey, reload)
OtherComponent.vue
import { reloadInjectKey } from '@/utils/types'
const reload = inject(reloadInjectKey)