Vue 3.0 組合式API

2021-11-03 16:37 更新

本節(jié)例子中代碼使用的單文件組件語法

#setup

一個組件選項,在創(chuàng)建組件之前執(zhí)行,一旦 props 被解析,并作為組合式 API 的入口點

  • 入?yún)ⅲ?/strong>
    • {Data} props
    • {SetupContext} context
  • 類型聲明

interface Data {
  [key: string]: unknown
}


interface SetupContext {
  attrs: Data
  slots: Slots
  emit: (event: string, ...args: unknown[]) => void
}


function setup(props: Data, context: SetupContext): Data

TIP

若要獲取傳遞給 setup() 的參數(shù)的類型推斷,請使用 defineComponent 是需要的。

  • 示例:

使用模板:

  <!-- MyBook.vue -->
  <template>
    <div>{{ readersNumber }} {{ book.title }}</div>
  </template>

  
  <script>
    import { ref, reactive } from 'vue'

  
    export default {
      setup() {
        const readersNumber = ref(0)
        const book = reactive({ title: 'Vue 3 Guide' })

  
        // expose to template
        return {
          readersNumber,
          book
        }
      }
    }
  </script>

使用渲染函數(shù):

  // MyBook.vue

  
  import { h, ref, reactive } from 'vue'

  
  export default {
    setup() {
      const readersNumber = ref(0)
      const book = reactive({ title: 'Vue 3 Guide' })
      // 請注意,我們需要在這里顯式地暴露ref值
      return () => h('div', [readersNumber.value, book.title])
    }
  }

#生命周期鉤子

可以使用直接導入的 onX 函數(shù)注冊生命周期鉤子:

import { onMounted, onUpdated, onUnmounted } from 'vue'


const MyComponent = {
  setup() {
    onMounted(() => {
      console.log('mounted!')
    })
    onUpdated(() => {
      console.log('updated!')
    })
    onUnmounted(() => {
      console.log('unmounted!')
    })
  }
}

這些生命周期鉤子注冊函數(shù)只能在 setup() 期間同步使用,因為它們依賴于內(nèi)部全局狀態(tài)來定位當前活動實例 (此時正在調(diào)用其 setup() 的組件實例)。在沒有當前活動實例的情況下調(diào)用它們將導致錯誤。

組件實例上下文也是在生命周期鉤子的同步執(zhí)行期間設置的,因此在生命周期鉤子內(nèi)同步創(chuàng)建的偵聽器和計算屬性也會在組件卸載時自動刪除。

選項 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

provideinject 啟用依賴注入。只有在使用當前活動實例的 setup() 期間才能調(diào)用這兩者。

  • 類型聲明

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

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 允許訪問對高級使用或庫創(chuàng)建者有用的內(nèi)部組件實例。

import { getCurrentInstance } from 'vue'


const MyComponent = {
  setup() {
    const internalInstance = getCurrentInstance()


    internalInstance.appContext.config.globalProperties // access to globalProperties
  }
}

getCurrentInstance 僅在安裝或生命周期掛鉤期間有效。

在安裝程序或生命周期掛鉤之外使用時,請在setup上調(diào)用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
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號