如何在 Vue3 的 setup 中使用 $refs


方法一:借助 ref() 函數

通過 ref 函數,依然可以實現類似 this.$refs 的功能。

首先在 setup 中定義一個 Ref 變量

import { defineComponent, ref, onMount } from 'vue'

defineComponent({
  setup() {
    const divRef = ref(null)

    onMount(() => {
      console.log(divRef.value)
    })
    
    return {
      divRef
    }
  }
})

然后將這個 divRef 變量掛載到 DOM 上

<template>
  <div ref="divRef" />
</template>

這樣當 onMount 鈎子被觸發的時候,div 的 DOM 會在控制台打印出來。

另外 ref 也能實現動態關聯,具體實現可以參考文章 《$refs and the Vue 3 Composition API》

方法二:找到 this

通過 getCurrentInstance() 可以獲得 vue 實例對象。

我們稍微改造下上文的代碼

import { defineComponent, getCurrentInstance, onMount } from 'vue'

defineComponent({
  setup() {
    onMount(() => {
      console.log(getCurrentInstance().ctx.$refs.divRef)
    })
  }
})
<template>
  <div ref="divRef" />
</template>

注意,使用 getCurrentInstance 是有一些限制的,可以參考官方說明


免責聲明!

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



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