vue中實(shí)時(shí)監(jiān)聽div元素盒子的寬高方法
在Vue中實(shí)時(shí)監(jiān)聽div
盒子的寬高可以使用resize
事件結(jié)合refs
來實(shí)現(xiàn)。
首先,在div
盒子上添加一個(gè)ref
屬性,例如:
<div ref="box"></div>
然后,在Vue組件的mounted
生命周期鉤子中添加事件監(jiān)聽:
mounted() { window.addEventListener('resize', this.handleResize) },
在Vue組件的methods
中定義handleResize
方法來處理寬高變化:
methods: { handleResize() { const width = this.$refs.box.offsetWidth; const height = this.$refs.box.offsetHeight; // 在這里處理寬高變化的邏輯 console.log('盒子寬度:', width, '盒子高度:', height); } },
這樣,每當(dāng)窗口大小改變時(shí),handleResize
方法將被調(diào)用并獲取到最新的寬高值。你可以在該方法中處理寬高變化的邏輯,例如更新數(shù)據(jù)、觸發(fā)其他操作等。
記得在Vue組件銷毀時(shí),移除事件監(jiān)聽:
beforeDestroy() { window.removeEventListener('resize', this.handleResize) },
這樣就能實(shí)時(shí)監(jiān)聽div
盒子的寬高了。
補(bǔ)充:vue如何實(shí)現(xiàn)實(shí)時(shí)監(jiān)聽頁面寬度高度變化
運(yùn)用的主要技術(shù):watch監(jiān)聽
話不多說直接上代碼,自行研究
<template> <div class="rightContainer"> <h1>監(jiān)聽頁面寬高</h1> <h2>當(dāng)前整個(gè)頁面寬度{{ windowWidth }}px</h2> <h2>當(dāng)前整個(gè)頁面高度{{ windowHeight }}px</h2> </div> </template> <script> export default { name: 'WatchsHW', data() { return { windowHeight: document.body.clientHeight, windowWidth: document.body.clientWidth } }, watch: { // 監(jiān)聽頁面高度 windowHeight(val) { console.log('實(shí)時(shí)屏幕高度:', val, this.windowHeight) }, // 監(jiān)聽頁面寬度 windowWidth(val) { console.log('實(shí)時(shí)屏幕寬度:', val, this.windowHeight) } }, mounted() { // <!--把window.onresize事件掛在到mounted函數(shù)上--> window.onresize = () => { return (() => { this.windowHeight = document.documentElement.clientHeight // 高 this.windowWidth = document.documentElement.clientWidth // 寬 })() } }, methods: { } } </script> <style lang="scss" scoped> .rightContainer{ width: 100%; text-align: center; overflow: hidden; } </style>
總結(jié)
到此這篇關(guān)于vue中實(shí)時(shí)監(jiān)聽div元素盒子寬高的文章就介紹到這了,更多相關(guān)vue實(shí)時(shí)監(jiān)聽div寬高內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
elementUI Table組件實(shí)現(xiàn)表頭吸頂效果(示例代碼)
文章介紹了如何在vue2.6+和elementUI環(huán)境下實(shí)現(xiàn)el-table組件的表頭吸頂效果,通過添加樣式、注冊(cè)指令、引入指令并在父元素中避免使用overflow:hidden,可以實(shí)現(xiàn)場景下表頭始終可見,本文通過實(shí)例代碼介紹的非常詳細(xì),感興趣的朋友一起看看吧2025-01-01vue2.x數(shù)組劫持原理的實(shí)現(xiàn)
這篇文章主要介紹了vue2.x數(shù)組劫持原理的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04Vue實(shí)現(xiàn)輸入框回車發(fā)送和粘貼文本與圖片功能
這篇文章主要為大家詳細(xì)介紹了Vue如何實(shí)現(xiàn)聊天輸入框回車發(fā)送、粘貼文本(包括HTML)、粘貼圖片等功能,文中的實(shí)現(xiàn)方法講解詳細(xì),需要的可以參考一下2022-05-05