一,需求概述
直接举例子来说明吧,我想要做的是,遍历这几个菜单,获取他们的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元素和操作的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/qdvuejs/10926.html