Vue 3.0 组合式API

#setup

一个组件选项,在创建组件之前执行,一旦 props 被解析,并作为组合式 API 的入口点

  • 入参:
    • {Data} props
    • {SetupContext} context
  • 类型声明

 
 
  1. interface Data {
  2. [key: string]: unknown
  3. }
  4. interface SetupContext {
  5. attrs: Data
  6. slots: Slots
  7. emit: (event: string, ...args: unknown[]) => void
  8. }
  9. function setup(props: Data, context: SetupContext): Data

TIP

若要获取传递给 setup() 的参数的类型推断,请使用 defineComponent 是需要的。

  • 示例:

使用模板:

 
 
  1. <!-- MyBook.vue -->
  2. <template>
  3. <div>{ { readersNumber }} { { book.title }}</div>
  4. </template>
  5. <script>
  6. import { ref, reactive } from 'vue'
  7. export default {
  8. setup() {
  9. const readersNumber = ref(0)
  10. const book = reactive({ title: 'Vue 3 Guide' })
  11. // expose to template
  12. return {
  13. readersNumber,
  14. book
  15. }
  16. }
  17. }
  18. </script>

使用渲染函数:

 
 
  1. // MyBook.vue
  2. import { h, ref, reactive } from 'vue'
  3. export default {
  4. setup() {
  5. const readersNumber = ref(0)
  6. const book = reactive({ title: 'Vue 3 Guide' })
  7. // 请注意,我们需要在这里显式地暴露ref值
  8. return () => h('div', [readersNumber.value, book.title])
  9. }
  10. }

#生命周期钩子

可以使用直接导入的 onX 函数注册生命周期钩子:

 
 
  1. import { onMounted, onUpdated, onUnmounted } from 'vue'
  2. const MyComponent = {
  3. setup() {
  4. onMounted(() => {
  5. console.log('mounted!')
  6. })
  7. onUpdated(() => {
  8. console.log('updated!')
  9. })
  10. onUnmounted(() => {
  11. console.log('unmounted!')
  12. })
  13. }
  14. }

这些生命周期钩子注册函数只能在 setup() 期间同步使用,因为它们依赖于内部全局状态来定位当前活动实例 (此时正在调用其 setup() 的组件实例)。在没有当前活动实例的情况下调用它们将导致错误。

组件实例上下文也是在生命周期钩子的同步执行期间设置的,因此在生命周期钩子内同步创建的侦听器和计算属性也会在组件卸载时自动删除。

选项 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
  • 参考组合式 API 生命周期钩子

#Provide / Inject

provide 和 inject 启用依赖注入。只有在使用当前活动实例的 setup() 期间才能调用这两者。

  • 类型声明

 
 
  1. interface InjectionKey<T> extends Symbol {}
  2. function provide<T>(key: InjectionKey<T> | string, value: T): void
  3. // without default value
  4. function inject<T>(key: InjectionKey<T> | string): T | undefined
  5. // with default value
  6. function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T

Vue 提供了一个 InjectionKey 接口,该接口是扩展 Symbol 的泛型类型。它可用于在提供者和消费者之间同步注入值的类型:

 
 
  1. import { InjectionKey, provide, inject } from 'vue'
  2. const key: InjectionKey<string> = Symbol()
  3. provide(key, 'foo') // 提供非字符串值将导致错误
  4. const foo = inject(key) // foo 的类型: string | undefined

如果使用字符串 key 或非类型化 symbols,则需要显式声明注入值的类型:

 
 
  1. const foo = inject<string>('foo') // string | undefined

  • 参考

#getCurrentInstance

getCurrentInstance 允许访问对高级使用或库创建者有用的内部组件实例。

 
 
  1. import { getCurrentInstance } from 'vue'
  2. const MyComponent = {
  3. setup() {
  4. const internalInstance = getCurrentInstance()
  5. internalInstance.appContext.config.globalProperties // access to globalProperties
  6. }
  7. }

getCurrentInstance 仅在安装或生命周期挂钩期间有效。

在安装程序或生命周期挂钩之外使用时,请在setup上调用getCurrentInstance(),并改用该实例。

 
 
  1. const MyComponent = {
  2. setup() {
  3. const internalInstance = getCurrentInstance() // works
  4. const id = useComponentId() // works
  5. const handleClick = () => {
  6. getCurrentInstance() // doesn't work
  7. useComponentId() // doesn't work
  8. internalInstance // works
  9. }
  10. onMounted(() => {
  11. getCurrentInstance() // works
  12. })
  13. return () =>
  14. h(
  15. 'button',
  16. {
  17. onClick: handleClick
  18. },
  19. `uid: ${id}`
  20. )
  21. }
  22. }
  23. // also works if called on a composable
  24. function useComponentId() {
  25. return getCurrentInstance().uid
  26. }

猜你喜欢

转载自blog.csdn.net/2201_75866484/article/details/129943705
今日推荐