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. css3 - 新版支付宝 账单页面滑动时月份栏被下一个月给顶上去是什么效果2. docker安装后出现Cannot connect to the Docker daemon.3. docker start -a dockername 老是卡住,什么情况?4. javascript - 关于js原生事件的绑定与解除绑定5. python - requests post问题6. mysql group by多个字段7. javascript - vuex 参数绑定问题求解8. docker镜像push报错9. javascript - Vue 自定义控件v-model双向绑定10. javascript - js 面向对象

网公网安备