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渲染完之后触发的
回答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
相关文章:
1. pdo_mysql 值自增写法2. Python, for-else, while-else是否造成了语义歧义 ( 增加心智负担 )?3. MYSQL 运算的问题4. javascript - js 对中文进行MD5加密和python结果不一样。5. javascript - 微信公号里采用七牛上传视频部分手机不能选择文件6. mysql sql where id in(25,12,87) 结果集如何用按照 25 12 87排序?7. mysql多表查询8. PHP中的$this代表当前的类还是方法?9. python3.x - python多进程,不能在同一窗口吗10. 关于python爬虫的问题

网公网安备