方法一:借助 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
是有一些限制的,可以參考官方說明