vue3中獲取dom元素和操作實現(xiàn)方法
一、需求概述
直接舉例子來說明吧,我想要做的是,遍歷這幾個菜單,獲取他們的dom元素的寬度。當文字dom元素寬度太長的話,需要滾動顯示文本。
二、實現(xiàn)思路
對應(yīng)的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>
對應(yīng)的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的子節(jié)點
const menu_item = ref(null); menu_item.value.children
3:獲取某個元素節(jié)點的寬度
上文已經(jīng)獲取到dom節(jié)點,這里用vNode替代,于是該節(jié)點的寬度:
vNode.offsetWidth
有的時候,我們想通過vNode.style.width來獲取。但是它只能獲取js給定的width,無法獲取css給定的width。所以這種方式獲取到的會是空。
4:給某個dom節(jié)點添加class
vNode.classList.add('newClass')
四、獲取到dom節(jié)點之后修改樣式
主要就是取到dom元素節(jié)點之后。設(shè)置style屬性
headerOrangeMask: require('@/assets/img/header-blue-mask.png'), //首頁頂部的我的圖標
const myMask = ref(null); nextTick(() => { myMask.value.style.backgroundImage = `url(${headerOrangeMask})`; //設(shè)置背景圖片 });
五、父組件調(diào)用子組件的函數(shù)方法
1:第一步,子組件暴露要被父組件調(diào)用的方法
// 主動暴露childMethod方法 defineExpose({ noticeSwiper }); //公告輪播-父組件請求完成后調(diào)用 function noticeSwiper() { console.log("子組件中的方法執(zhí)行了") }
2:第二步,父組件中取得子組件的dom并調(diào)用方法
<Notice ref="noticeNode"></Notice> const noticeNode = ref(null); //公告組件的node //獲取公告信息 function getNotice() { store.dispatch('notice/getNoticeList').then(() => { noticeNode.value.noticeSwiper(); //調(diào)用子組件方法輪播公告 }); }
總結(jié)
到此這篇關(guān)于vue3中獲取dom元素和操作實現(xiàn)方法的文章就介紹到這了,更多相關(guān)vue3獲取dom元素和操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue?cli3?項目中如何使用axios發(fā)送post請求
這篇文章主要介紹了vue?cli3?項目中如何使用axios發(fā)送post請求,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04關(guān)于Vue源碼vm.$watch()內(nèi)部原理詳解
這篇文章主要介紹了關(guān)于Vue源碼vm.$watch()內(nèi)部原理詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04