今天遇到一个问题,就是在Vue3组件中需要获取template中的元素节点,使用GetElementById返回的却是null,网上查找了好些资料,才发需要使用ref。
1.Vue3 中 ref 访问单个元素
<template>
<div ref="hello">我爱北京天安门</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
const hello = ref<any>(null);
onMounted(() => {
console.log(hello.value); // <div>我爱北京天安门</div>
});
</script>
注意:
- 变量名称必须要与 ref 命名的属性名称一致。
- 通过 hello.value 的形式获取 DOM 元素。
- 必须要在 DOM 渲染完成后才可以获取 hello.value,否则就是 null。
2.Vue3 中 ref 访问v-for元素
<template>
<ul>
<li v-for="item in 10" ref="itemRefs">
<p>{
{item}} - 同学</p>
</li>
</ul>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
const itemRefs = ref<any>([]);
onMounted(() => {
console.log(itemRefs.value);
});
</script>
注意,这里取到的是<li>元素节点,要取到<p>,则需要从childNodes中获取
itemRefs.value[i].childNodes[0]