javascript - vue 如何獲取組件自身高度
問題描述
由于要做一個可變化長高的彈出框,需要定位,彈出框可能在底部彈出也可能在頭部彈出,但內(nèi)容由于是可變的,需要計算它的高度來顯示向上彈還是向下彈,目前在組件內(nèi)如何得到他的高度目前我的做法是在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);}
打印結(jié)果curHeight為undefind,求辦法
問題解答
回答1:element.offsetHeight// 在vue中請使用ref獲取真實DOM// 在mounted鉤子中調(diào)用,該鉤子是DOM渲染完之后觸發(fā)的
回答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節(jié)點還沒有插入進頁面吧,需要在mounted勾子函數(shù)中調(diào)用而且獲取到元素的高度,是用dom.clientHeight吧,或者dom.getBoundingClientRect().height吧
回答4:@林小新 由于我在調(diào)用時,使用了v-if所以每次設(shè)為true它才會創(chuàng)建,所以可以放在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
相關(guān)文章:
1. angular.js - webpack build后的angularjs路由跳轉(zhuǎn)問題2. 數(shù)組按鍵值封裝!3. java - web項目中,用戶登陸信息存儲在session中好 還是cookie中好,取決于什么?4. mysql - 根據(jù)一個字段查找另一個字段重復(fù)的數(shù)據(jù)?并刪除相同的記錄,保留其中一個。5. mysql - 查詢字段做了索引為什么不起效,還有查詢一個月的時候數(shù)據(jù)都是全部出來的,如果分拆3次的話就沒問題,為什么呢。6. 單擊登錄按鈕無反應(yīng)7. mysql - 大部分數(shù)據(jù)沒有行溢出的text字段是否需要拆表8. ubuntu - mysql 連接問題9. Mysql取下一條記錄10. mysql儲存json錯誤
