Home > Article > Web Front-end > How to get element node through ref in vue3
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
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...
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
This way you can access it
document.querySelector(选择器) document.getElementById(id选择器) document.getElementsByClassName(class选择器)
<template> <div ref='divDom'></div> </template> <script setup> import { ref} from 'vue' const divDom = ref(null); onMounted(()=>{ console.log('获取dom元素',divDom) })
<template> <div ref='getDivDom' v-for="item in list" :data-id="item.id"></div> </template> <script setup> import { ref} from 'vue' const divDomList = ref(new Map()); const getDivDom = el=>{ if(el){ divDomList.set(el.dataset['id'],el) } } // const el =divDomList.get(id) // 根据list数据中的id值 获取对应的dom元素
<template> <swiper @swiper='getSwiper'></swiper > </template> <script setup> import swiper from 'swiper' import { ref} from 'vue' const swiperDom= ref(null); const getSwiper= el=>{ swiperDom.value = el; }
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!