1. 原生js获取dom元素:
document.querySelector(选择器)
document.getElementById(id选择器)
document.getElementsByClassName(class选择器)
....
2. ref获取单个dom元素:
<template>
<div ref='divDom'></div>
</template>
<script setup>
import { ref} from 'vue'
const divDom = ref(null);
onMounted(()=>{
console.log('获取dom元素',divDom)
})
</script>
3. ref获取v-for循环中的dom元素:
<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元素
</script>
4. 在swiper中获取swiper的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;
}
</script>
|