在 Vue3 組合式 API 中,setup 函數在組件實例化之前執行,所以無法訪問到組件實例化之后的 $refs 屬性,也就是無法獲取組件實例 this
。
官方文檔給出的獲取組件實例方法 getCurrentInstance,它只適合於開發環境中,打包上線之后無法獲取到組件實例 this。
在使用組合式 API 時,響應式引用和模板引用的概念是統一的,即通過 ref() 來獲取組件節點。
<template>
<audio ref="audio" />
</template>
<script lang="ts">
import { defineComponent, ref, Ref } from 'vue'
export default defineComponent({
name: 'Demo',
setup() {
let audio: Ref<any>
audio = ref(null)
return { audio }
}
})
</script>
注意:在節點中聲明的 ref 名稱必須與 setup 函數內的變量名稱保持一致;若你使用的是 TS,你必須要為變量指示類型為 any。