vue3 应用:使用ref获取dom的方法
介绍一个vue3 应用:使用ref获取dom的方法。
ref在我们开发项目当中很重要的,在 Vue 中使用 ref
可以提高代码的可读性和维护性,因为它直接标识出了组件中需要操作的具体元素或组件实例。这使得团队合作、代码审查和后续功能更新更加高效。总结来说,ref
在 Vue 中是一个非常有用的工具,不仅使得操作 DOM 更加方便和直观,还能够提升组件间通信的灵活性和效率。正确使用 ref
可以帮助开发者更好地管理和操作 DOM 元素以及组件实例,从而实现复杂的前端交互和 UI 动效。
通过ref直接拿到dom引用
<template> <div> <div ref="sectionRef">1111111</div> </div> </template> <script setup> 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> <div ref="listRef"> <div @click="higherAction(index)" v-for="(item, index) in state.list" :key="index"> <span>{{item}}</span> </div> </div> </div> </template> <script setup> 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> <div> <div :ref="setRefAction" @click="higherAction(index)" v-for="(item, index) in state.list" :key="index"> <span>{{item}}</span> </div> </div> </div> </template> <script setup> 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,大家可以试试吧!
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。