vue3中使用ref获取dom的操作代码 |
前言本期文章我将给大家带来的是vue3中用ref获取dom的操作,ref在我们开发项目当中很重要的,在 Vue 中使用 通过ref直接拿到dom引用<template>
<div class="demo1-container">
<div ref="sectionRef" class="ref-section">1111111</div>
</div>
</template>
<script setup lang="ts">
import {onMounted, ref} from 'vue'
const sectionRef = ref(null)
onMounted(() => {
console.log(sectionRef.value)
})
</script>
在这里我们要注意的是当在div标签中用
单一dom元素或者个数较少的场景 通过父容器的ref遍历拿到dom引用<template>
<div class="demo2-container">
<div ref="listRef" class="list-section">
<div @click="higherAction(index)" class="list-item" v-for="(item, index) in state.list" :key="index">
<span>{{item}}</span>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
const listRef = ref()
const state = reactive({
list: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
})
onMounted(()=>{
console.log(listRef.value)
})
</script>
<style scoped>
.demo2-container {
width: 200px;
height: 400px;
border: 1px solid #000;
overflow: auto;
}
</style>
通过对父元素添加了ref属性,并声明了一个与ref属性名称相同的变量listRef,此时通过listRef.value会获得包含子元素的dom对象,然后我们就可以此时通过
通过:ref将dom引用放到数组中<template>
<div class="demo2-container">
<div class="list-section">
<div :ref="setRefAction" @click="higherAction(index)" class="list-item" v-for="(item, index) in state.list" :key="index">
<span>{{item}}</span>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive ,ref} from 'vue'
const state = reactive({
list: [1, 2, 3, 4, 5, 6, 7],
refList: []
})
const index = ref(null)
const setRefAction = (el: any) => {
state.refList.push(el);
}
const higherAction = (index) => {
console.log(state.refList[index])
}
onMounted( () => {
console.log(state.refList);
setRefAction(index)
})
</script>
<style scoped>
.demo2-container {
width: 200px;
height: 400px;
border: 1px solid #000;
overflow: auto;
}
.list-item {
background-color: pink;
border: 1px solid #000;
}
</style>
这种情况下,我们可以通过动态设置ref的形式进行设置ref,这样我们就可以获取到一个ref的数组,结果如下
当我们点击哪个就会获取哪个的dom,这样我们简单多了 到此这篇关于vue3中使用ref获取dom的操作代码的文章就介绍到这了,更多相关vue3 ref获取dom内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持! |