如何在Vue3中通过ref获取dom元素,这里说一下我遇到的情况和使用方式
情况一:只是单纯的获取某个dom元素
这种情况比较简单,直接在js中通过ref定义一个和html中元素上ref相同名字的变量即可
例子:
<template>
<div class="box" ref="boxRef">
box
</div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
const boxRef = ref<HTMLElement>() // 这里定义一个和div中ref名字一样的变量名即可
onMounted(() => {
if (boxRef.value) {
console.log(boxRef.value)
}
})
</script>
情况二:在for循环中获取dom元素
这种情况下,我们可以通过动态设置ref的形式进行设置ref,这样我们就可以获取到一个ref的数组
例子:
<template>
<div class="box">
<div v-for="item in 10" :key="item" :ref="setBoxRef">
box
</div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
const boxRefs = ref<HTMLElement[]>([])
const setBoxRef = (el: any) => {
if (el) {
boxRefs.value.push(el)
}
}
onMounted(() => {
console.log(boxRefs.value)
})
</script>
情况三:获取ref中的ref
这种情况我们不能像Vue2的方式一样通过
refs.refs
或者.children
的形式,因为你会发现,这些方法都不能用了
所以要解决这个问题,我们需要借助Vue3提供的新的方法getCurrentInstance
需要注意的是,getCurrentInstance
只能在setup
或者生命周期
中使用才有效
具体参考官方文档:https://v3.cn.vuejs.org/api/composition-api.html#getcurrentinstance
例子:
<template>
<div class="box" ref="boxRef">
<div ref="boxInnerRef">
<div ref="innerRef">
innerRef
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, getCurrentInstance } from 'vue';
onMounted(() => {
const instance = getCurrentInstance()
if (instance) {
console.log(instance.refs)
}
})
</script>
我们可以看到,不管多少层的ref
,Vue3都给处理成了一层的Object形式,我们就能很方便的拿到自己需要的dom元素了