[Vue]如何使用 Vue3 的模板引用?


在 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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM