Home > Web Front-end > Vue.js > How to get element node through ref in vue3

How to get element node through ref in vue3

PHPz
Release: 2023-05-16 12:25:06
forward
5156 people have browsed it

Get element nodes through ref

ref In vue2, it can be said to simplify the js native document.getElementById("#id") operation. Of course, the same is true in vue3

First, give the element you want to get a ref attribute

How to get element node through ref in vue3

Then, create the ref object, and then His value can be accessed

But. This can be accessed in the setup, but the value printed directly is null...

How to get element node through ref in vue3

Because the execution time of the setup function must precede the html tag Rendering, so we cannot initialize the box tag directly in the setup function.

In the life cycle function, the setup function is executed between beforeCreate and Created

If there is initialization or similar operations, you need to borrow onMounted in the life cycle function

How to get element node through ref in vue3

This way you can access it

How to get element node through ref in vue3

Summary of several ways to get ref elements

1. Get dom elements with native js

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

2. ref gets a single dom element

<template>
   <div ref=&#39;divDom&#39;></div> 
</template>
<script setup>
import { ref} from &#39;vue&#39;
const divDom = ref(null);
onMounted(()=>{
    console.log(&#39;获取dom元素&#39;,divDom)
})
Copy after login

3. ref gets the dom element in the v-for loop

<template>
   <div ref=&#39;getDivDom&#39; v-for="item in list" :data-id="item.id"></div> 
</template>
<script setup>
import { ref} from &#39;vue&#39;
const divDomList = ref(new Map());

const getDivDom = el=>{
    if(el){
        divDomList.set(el.dataset[&#39;id&#39;],el) 
    }
}
// const el =divDomList.get(id) // 根据list数据中的id值 获取对应的dom元素
Copy after login

4. Get the dom element of swiper in swiper

<template>
   <swiper @swiper=&#39;getSwiper&#39;></swiper > 
</template>
<script setup>
import swiper from &#39;swiper&#39;
import { ref} from &#39;vue&#39;
const swiperDom= ref(null);

const getSwiper= el=>{
    swiperDom.value = el;
}
Copy after login

The above is the detailed content of How to get element node through ref in vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template