Vue3: 获取元素DOM的方法

Vue3中获取dom的方法有两种 : ref模板引用和传统方法

1.ref模板引用

模板引用是官方提出的方法,请看下面的例子:

JavaScript 复制代码
<template>
    <canvas ref="solarCanvas" id="solar" width="1300" height="900"></canvas>
</template>

<script setup>
import {  onMounted, ref } from 'vue'

const solarCanvas = ref(null)
onMounted(() => {
  console.log(solarCanvas.value)//HTMLCanvasElement{...}
})
</script>

这里要注意的是只可以在组件挂载后 才能访问模板引用 ,上面的例子中onMounted执行时组件已经挂载了 , 所以打印solarCanvas有值。

JavaScript 复制代码
<template>
    <canvas ref="solarCanvas" id="solar" width="1300" height="900"></canvas>
</template>

<script setup>
import {  onMounted, ref } from 'vue'

const solarCanvas = ref(null)
console.log(solarCanvas.value)//null
</script>

反之,如果这样写打印出来的值就为null,因为此时组件还没有挂载完成。

2.传统方法

传统方法就是指使用JS原生的获取dom的方法,如:getElementByIdquerySelector等。请看下面的例子:

JavaScript 复制代码
<template>
    <canvas id="solar" width="1300" height="900"></canvas>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'

onMounted(() => {
  const canvas = document.getElementById('solar')
  console.log(canvas)//HTMLCanvasElement{...}
})
</script>

同样的道理,如果使用传统方法获取dom时,组件没有挂载完成的话,那么获取到的也是null

JavaScript 复制代码
<template>
    <canvas id="solar" width="1300" height="900"></canvas>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'

const canvas = document.getElementById('solar')
onMounted(() => {
  console.log(canvas)//null
})
</script>

3.结论

在Vue3当获取DOM的方法主要有两个:模板引用和传统方法。

但需要注意的是,无论使用哪种方法都只有在组件挂载之后才能获取到DOM,可以使用watchonMounted确保自己已经获取到DOM。

参考资料

Vue3官方文档: 模板引用

相关推荐
hunterandroid12 分钟前
Paging 3 RemoteMediator 实战:构建离线优先的分页列表
android·前端
Underwood_1715 分钟前
星级评价——了解useState
前端
hunterandroid18 分钟前
[鸿蒙从零到一] ArkUI 组件化实战:构建可复用、可组合的自定义组件
前端·华为·架构
一只公羊21 分钟前
iPhone摄像头 在开发/调试过程中强行停止 App,导致 `AVCaptureSession` 没有被正常释放
前端
活于未来24 分钟前
从零搭建期权波动率曲面可视化平台:FastAPI + Vue 3 实战
vue.js
橘子海全栈攻城狮31 分钟前
【最新源码】基于SpringBoot + Vue的超市管理系统的设计与实现D002
java·开发语言·vue.js·spring boot·后端·spring
浮江雾1 小时前
Flutter第十节-----Flutter布局与组件全解析
android·开发语言·前端·学习·flutter·入门
xcLeigh1 小时前
Doubao-Seed-Evolving大模型接入教程|搭建全品类提示词+AI工具导航网页
前端·人工智能·python·ai·html·ai开发·豆包
巴勒个啦3 小时前
Vue 3.6 Vapor Mode 实战:我把一个 Vue3 项目的渲染性能提升了 4 倍
前端·angular.js