vue.js 获取当前屏幕的宽度_用Vuejs获取元素高度

I want to get the height of a div in order to make the height of another div matching it. I used the method clientHeight, but It doesn't return me the good value (smaller value). Actually, It seems to return a height before all elements are charged.

After some research online, I tried to put a window.load() to delay until everything is charged but it doesn't work as well. Some ideas ?

mounted () {

this.matchHeight()

},

matchHeight () {

let height = document.getElementById('info-box').clientHeight

}

Some text

some list

解决方案

The way you are doing it is fine. But there is another vue specific way via a ref attribute.

mounted () {

this.matchHeight()

},

matchHeight () {

let height = this.$refs.infoBox.clientHeight;

}

Some text

>

some list

In this case, since you are just getting the value it really doesn't matter whether you use your original getElementById approach or the vue specific ref approach. However if you were setting the value on the element then it's much better to use the ref approach so that vue understands that the value has changed and won't possibly overwrite the value with the original value if it needs to update that node in the DOM.

Update

A few people had left comments that the above solution didn't work for them. That solution provided the concepts but not full working code as example, so I have augmented my answer with the code below which demonstrates the concepts.

var app = new Vue({

el: '#app',

data: function () {

return {

leftColStyles: { },

lines: ['one', 'two','three']

}

},

methods: {

matchHeight() {

var heightString = this.$refs.infoBox.clientHeight + 'px';

Vue.set(this.leftColStyles, 'height', heightString);

}

},

mounted() {

this.matchHeight();

}

});

.columns{width:300px}

.left-column {float:left; width:200px; border:solid 1px black}

.right-column {float:right; border:solid 1px blue; }

Some text

Here is a screenshot of the results in the browser:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值