vue3中用ref获取dom的操作
前言
大家好我是你们的扯蛋蛋,本期文章我将给大家带来的是vue3中用ref获取dom的操作,ref在我们开发项目当中很重要的,在 Vue 中使用 ref
可以提高代码的可读性和维护性,因为它直接标识出了组件中需要操作的具体元素或组件实例。这使得团队合作、代码审查和后续功能更新更加高效。总结来说,ref
在 Vue 中是一个非常有用的工具,不仅使得操作 DOM 更加方便和直观,还能够提升组件间通信的灵活性和效率。正确使用 ref
可以帮助开发者更好地管理和操作 DOM 元素以及组件实例,从而实现复杂的前端交互和 UI 动效。接下来我就一一道来吧
1. 通过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标签中用 ref="sectionRef"
,之后在声明响应式变量的时候,要用sectionRef
命名,这个是一定要的,然后我们通过 sectionRef.value 的形式即可获取该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对象,然后我们就可以此时通过listRef.value.children[index]
的形式获取子元素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,这样我们简单多了
如觉得本文对你有帮助的话,欢迎点赞❤❤❤,写作不易,持续输出的背后是无数个日夜的积累,您的点赞是持续写作的动力,感谢支持!有什么写错的,需要增加的可以在评论区留言 谢谢大家支持
转载自:https://juejin.cn/post/7384611550386946111