likes
comments
collection
share

Vue3: 获取元素DOM的方法

作者站长头像
站长
· 阅读数 6

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

1.ref模板引用

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

<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有值。

<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等。请看下面的例子:

<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

<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官方文档: 模板引用

转载自:https://juejin.cn/post/7359833391192490025
评论
请登录