vue3中获取dom元素和操作实现方法
作者:笑道三千
ref是Vue3中一个非常重要的功能,它可以用来获取DOM节点,从而实现对DOM节点的操作,下面这篇文章主要给大家介绍了关于vue3中获取dom元素和操作实现的相关资料,需要的朋友可以参考下
一、需求概述
直接举例子来说明吧,我想要做的是,遍历这几个菜单,获取他们的dom元素的宽度。当文字dom元素宽度太长的话,需要滚动显示文本。

二、实现思路
对应的html:
<div class="icon-box" ref="menu_item">
<div
class="menu-box"
v-for="(item, index) in iconMenus"
:key="index"
@click="clickItem(item)"
>
<span :class="[item.imageRef, 'item-image']"></span>
<div class="item-content">
{{ item.menuName }}
</div>
</div>
</div>对应的css:
.menu-box {
width: 144px;
height: 144px;
margin-top: 5px;
flex-shrink: 0;
position: relative;
overflow: hidden;
.item-image {
display: block;
font-size: 60px;
padding: 15px;
&::before {
color: v-bind(zeroTheme);
}
}
.item-content {
font-size: 26px;
display: inline-block;
white-space: nowrap;
}
.item-content-flag {
font-size: 26px;
position: absolute;
display: inline-block;
white-space: nowrap;
left: 0;
bottom: 22px;
white-space: nowrap;
-webkit-animation: todayScroll 4s linear infinite;
animation: todayScroll 5s linear infinite;
}
}第一步:先通过ref获取最外层容器的dom:
const menu_item = ref(null);
第二步:遍历判断,给超长的dom添加class样式
menu_item.value.children.forEach(element => {
let parentWith = element.offsetWidth;
let childrenWith = element.children[1].offsetWidth;
if (childrenWith >= parentWith - 10) {
element.children[1].classList.add('item-content-flag');
}
});三、由此得到vue3中常用的dom操作
1:获取dom
<div class="icon-box" ref="menu_item"></div> const menu_item = ref(null);
2:获取dom的子节点
const menu_item = ref(null); menu_item.value.children
3:获取某个元素节点的宽度
上文已经获取到dom节点,这里用vNode替代,于是该节点的宽度:
vNode.offsetWidth
有的时候,我们想通过vNode.style.width来获取。但是它只能获取js给定的width,无法获取css给定的width。所以这种方式获取到的会是空。
4:给某个dom节点添加class
vNode.classList.add('newClass')四、获取到dom节点之后修改样式
主要就是取到dom元素节点之后。设置style属性
headerOrangeMask: require('@/assets/img/header-blue-mask.png'), //首页顶部的我的图标const myMask = ref(null);
nextTick(() => {
myMask.value.style.backgroundImage = `url(${headerOrangeMask})`; //设置背景图片
});五、父组件调用子组件的函数方法
1:第一步,子组件暴露要被父组件调用的方法
// 主动暴露childMethod方法
defineExpose({ noticeSwiper });
//公告轮播-父组件请求完成后调用
function noticeSwiper() {
console.log("子组件中的方法执行了")
}2:第二步,父组件中取得子组件的dom并调用方法
<Notice ref="noticeNode"></Notice>
const noticeNode = ref(null); //公告组件的node
//获取公告信息
function getNotice() {
store.dispatch('notice/getNoticeList').then(() => {
noticeNode.value.noticeSwiper(); //调用子组件方法轮播公告
});
}总结
到此这篇关于vue3中获取dom元素和操作实现方法的文章就介绍到这了,更多相关vue3获取dom元素和操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
