Vue3组件中使用ref解决GetElementById为空的问题

今天遇到一个问题,就是在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]

相关推荐

  1. Vue3组件使用ref解决GetElementById问题

    2023-12-07 15:34:07       59 阅读
  2. Vue3组件间通信-$refs和$parent使用

    2023-12-07 15:34:07       35 阅读
  3. vue3使用ref

    2023-12-07 15:34:07       37 阅读
  4. vue ref 和 $refs使用

    2023-12-07 15:34:07       56 阅读
  5. Vue3 各种ref

    2023-12-07 15:34:07       49 阅读
  6. Vue3reactive与ref

    2023-12-07 15:34:07       43 阅读
  7. vue3reactive和ref

    2023-12-07 15:34:07       23 阅读
  8. vue3reactive和ref

    2023-12-07 15:34:07       27 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-07 15:34:07       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-07 15:34:07       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-07 15:34:07       87 阅读
  4. Python语言-面向对象

    2023-12-07 15:34:07       96 阅读

热门阅读

  1. Vue中下载不同文件的几种方式

    2023-12-07 15:34:07       67 阅读
  2. 微信小程序中 不同页面如何传递参数

    2023-12-07 15:34:07       63 阅读
  3. STM32关键词提取

    2023-12-07 15:34:07       61 阅读
  4. 1.求两个数最大值

    2023-12-07 15:34:07       57 阅读
  5. Python里的OS模块

    2023-12-07 15:34:07       45 阅读
  6. Rust语言项目实战(九 - 完结) - 胜利与失败

    2023-12-07 15:34:07       53 阅读
  7. Ubuntu 安装高版本FFmpeg

    2023-12-07 15:34:07       64 阅读
  8. CSS选择器看一篇就够了

    2023-12-07 15:34:07       67 阅读
  9. Redis击穿(热点key失效)

    2023-12-07 15:34:07       66 阅读
  10. centos 源码编译gcc10.2

    2023-12-07 15:34:07       69 阅读