javascript - vue 如何獲取組件自身高度
問題描述
由于要做一個可變化長高的彈出框,需要定位,彈出框可能在底部彈出也可能在頭部彈出,但內容由于是可變的,需要計算它的高度來顯示向上彈還是向下彈,目前在組件內如何得到他的高度目前我的做法是在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渲染完之后觸發(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ù)中調用而且獲取到元素的高度,是用dom.clientHeight吧,或者dom.getBoundingClientRect().height吧
回答4:@林小新 由于我在調用時,使用了v-if所以每次設為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
相關文章:
1. 如何修改phpstudy的phpmyadmin放到其他地方2. java 排序的問題3. 我的html頁面一提交,網(wǎng)頁便顯示出了我的php代碼,求問是什么原因?4. 網(wǎng)絡傳輸協(xié)議 - 以下三種下載方式有什么不同?如何用python模擬下載器下載?5. angular.js - Angular路由和express路由的組合使用問題6. 我在centos容器里安裝docker,也就是在容器里安裝容器,報錯了?7. tp6表單令牌8. 老哥們求助啊9. php - mysql中,作為主鍵的字段,用int類型,是不是比用char類型的效率更高?10. django - 后臺返回的json數(shù)據(jù)經(jīng)過Base64加密,獲取時用python如何解密~!
