1、作用
从Vue引用或组件实例中检索底层DOM元素
使用案例
<script setup>
import { unrefElement } from '@vueuse/core'
import { onMounted, ref } from 'vue'
const div = ref() // will be bound to the <div> element
const hello = ref() // will be bound to the HelloWorld Component
onMounted(() => {
console.log(unrefElement(div)) // the <div> element
console.log(unrefElement(hello)) // the root element of the HelloWorld Component
})
</script>
<template>
<div ref="div" />
<HelloWorld ref="hello" />
</template>
源码解读
import type { MaybeElement, VueInstance, MaybeComputedElementRef } from '../utils'
import { toValue } from '../toValue'
export type UnRefElementReturn<T extends MaybeElement = MaybeElement> = T extends VueInstance ? Exclude<MaybeElement, VueInstance> : T | undefined
/**
* 得到 ref 或者 元素 或者 vue组件 的 dom 元素
*/
export function unrefElement<T extends MaybeElement>(elRef: MaybeComputedElementRef<T>): UnRefElementReturn<T> {
const plain = toValue(elRef)
return (plain as VueInstance)?.$el ?? plain
}