您的位置:首頁技術文章
文章詳情頁

javascript - vue 如何獲取組件自身高度

瀏覽:101日期:2023-05-10 18:57:55

問題描述

由于要做一個可變化長高的彈出框,需要定位,彈出框可能在底部彈出也可能在頭部彈出,但內容由于是可變的,需要計算它的高度來顯示向上彈還是向下彈,目前在組件內如何得到他的高度目前我的做法是在created()中使用classname得到組件的p但由于初始在data()中將組件高度默認了0,在created中改變data()中的height,但得不到p

created() {

let cur = document.querySelectorAll('p[class=’Pop-Over’]');console.log(cur);let curHeight = cur.height;console.log(curHeight);}

打印結果curHeight為undefind,求辦法

問題解答

回答1:

element.offsetHeight// 在vue中請使用ref獲取真實DOM// 在mounted鉤子中調用,該鉤子是DOM渲染完之后觸發的

回答2:

mounted () { this.$nextTick(() => {let cur = document.querySelectorAll('p[class=’Pop-Over’]');console.log(cur);let curHeight = cur.height;console.log(curHeight); })}回答3:

created勾子 dom節點還沒有插入進頁面吧,需要在mounted勾子函數中調用而且獲取到元素的高度,是用dom.clientHeight吧,或者dom.getBoundingClientRect().height吧

回答4:

@林小新 由于我在調用時,使用了v-if所以每次設為true它才會創建,所以可以放在created中,但你這樣也讓我知道了nextTick這個東西,沒用過,但先按你的試試。目前暫由于最外層p是沒有高度的,只能通過取子p的高度累加成為它的高度,這種做法只是折中解決,可能是我寫組件時沒有考慮到這些。

this.$nextTick(() => {

let cur = document.querySelectorAll('p[class=’Pop-Over’]');

//console.log(cur);

let curHeight = 0; cur[0].childNodes.forEach(function (item, index, array) {

// console.log(typeof item.clientHeight);

curHeight += (typeof item.clientHeight) === ’number’ ? item.clientHeight : 0; }); });

如果沒有更好答案,我會采納你的

回答5:

獲取實際的大小 .clientWidth和.clientHeight并沒有.height這種獲取方法,所以才undefined

標簽: JavaScript
相關文章:
国产综合久久一区二区三区