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. android - NavigationView 的侧滑菜单中如何保存新增项(通过程序添加)2. mysql服务无法启动1067错误,谁知道正确的解决方法?3. php - 第三方支付平台在很短时间内多次异步通知,订单多次确认收款4. php7.3.4中怎么开启pdo驱动5. jquery清除input type为password?6. 这段代码既不提示错误也看不到结果,请老师明示错在哪里,谢谢!7. tp5 不同控制器中的变量调用问题8. 老师 我是一个没有学过php语言的准毕业生 我希望您能帮我一下9. ueditor上传服务器提示后端配置项没有正常加载,求助!!!!!10. 提示语法错误语法错误: unexpected ’abstract’ (T_ABSTRACT)
