vue3组合式API

 

选项 API 生命周期选项和组合式 API 之间的映射

  • beforeCreate -> use setup()

  • created -> use 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() on setup 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
}
复制代码

 

 
posted @   偷熊计划  阅读(135)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示