选项 API 生命周期选项和组合式 API 之间的映射
-
-> usebeforeCreate
setup()
-
-> usecreated
setup()
-
beforeMount
->onBeforeMount
-
mounted
->onMounted
-
beforeUpdate
->onBeforeUpdate
-
updated
->onUpdated
-
beforeUnmount
->onBeforeUnmount
-
unmounted
->onUnmounted
-
errorCaptured
->onErrorCaptured
-
renderTracked
->onRenderTracked
-
renderTriggered
->onRenderTriggered
Provide / Inject
provide
和 inject
启用依赖注入。只有在使用当前活动实例的 setup()
期间才能调用这两者。
- 类型声明:
interface InjectionKey<T> extends Symbol {} function provide<T>(key: InjectionKey<T> | string, value: T): void // without default value function inject<T>(key: InjectionKey<T> | string): T | undefined // with default value function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T // with factory function inject<T>( key: InjectionKey<T> | string, defaultValue: () => T, treatDefaultAsFactory: true ): T
Vue 提供了一个 InjectionKey
接口,该接口是扩展 Symbol
的泛型类型。它可用于在提供者和消费者之间同步注入值的类型:
import { InjectionKey, provide, inject } from 'vue' const key: InjectionKey<string> = Symbol() provide(key, 'foo') // 提供非字符串值将导致错误 const foo = inject(key) // foo 的类型: string | undefined
如果使用字符串 key 或非类型化 symbols,则需要显式声明注入值的类型:
const foo = inject<string>('foo') // string | undefined
getCurrentInstance
getCurrentInstance
允许访问对高级用法或库创建者有用的内部组件实例.
import { getCurrentInstance } from 'vue' const MyComponent = { setup() { const internalInstance = getCurrentInstance() internalInstance.appContext.config.globalProperties // access to globalProperties } }
getCurrentInstance
only works during setup or Lifecycle Hooks(仅在设置或生命周期挂钩期间有效)
When using outside of setup or Lifecycle Hooks, please call
getCurrentInstance()
onsetup
and use the instance instead.(在setup或Lifecycle Hooks之外使用时,请在安装程序上调用getCurrentInstance()并改用实例。)
const MyComponent = { setup() { const internalInstance = getCurrentInstance() // works const id = useComponentId() // works const handleClick = () => { getCurrentInstance() // doesn't work useComponentId() // doesn't work internalInstance // works } onMounted(() => { getCurrentInstance() // works }) return () => h( 'button', { onClick: handleClick }, `uid: ${id}` ) } } // also works if called on a composable function useComponentId() { return getCurrentInstance().uid }
标签:组合式,const,setup,InjectionKey,getCurrentInstance,API,inject,key,vue3
From: https://www.cnblogs.com/vant-xie/p/16755733.html