Vue3 gets dom elements

In vue2, dom elements can be obtained through this.$refs.xxxx, but when using the combined API in vue3, there is no this. The following is the method of obtaining dom elements in vue3:

1. Obtaining DOM elements through js
Vue is just a framework of javascript, and native js methods can also be used naturally

document.querySelector(选择器)
document.getElementById(id)
document.getElementsByClassName(class)

Defect: In the vue project, it is usually component-based development, each component is relatively independent, but when the dom element is obtained through js, the dom element of the entire page is obtained, so it is possible to get unexpected element.

2. Obtain by ref

<script setup>
import {
      
       ref } from 'vue';

const test = ref();   // 通过ref获取dom元素,变量名必须要和dom元素上面的名字一样
console.log(test);
</script>

<template>
	<div ref="test">测试获取dom</div>
</template>

Note: When using ref, the variable name must be the same as the name on the dom element. That is, if you write ref="xxx" on the dom element, you also need to use const xxx = ref() when defining variables.

Defect: I feel that it is not very friendly to get dom elements in this way, because ref can also be used to create responsive objects, which is not very intuitive (at first glance, it is not sure that it is a dom element), and it will also limit you to get the name of the variable.

Guess you like

Origin blog.csdn.net/brilliantSt/article/details/130986496