【发布时间】:2016-07-22 20:37:40
【问题描述】:
我正在使用 Vue.js 创建一个组件,并将其插入到 DOM 中没有任何问题。一旦元素在 DOM 中,我想知道它的渲染高度 - 即,我想获得它的 offsetHeight。我不知道该怎么做 - 我一定错过了一些非常明显的东西。这是我尝试过的:
HTML:
<!-- vue instance -->
<div id="my-app">
<my-component></my-component>
</div>
<!-- component template -->
<template id="my-component">
<h1>Hello World</h1>
<p>Lorem ipsum dolor sit amet.</h1>
<pre>{{ myheight }}</pre>
</template>
Vue Javascript:
Vue.component('my-component',{
template: '#my-component',
computed: {
myheight: function(){
return this.offsetHeight;
}
}
});
Vue({ el: '#my-app' });
但它不起作用 - 'myheight' 最终为空。我认为问题可能在于它可能在将其插入 DOM 之前尝试生成计算属性,因此我尝试了以下操作,而不是使用计算属性:
Vue.component('my-component',{
template: '#my-component',
data: function(){
return {
myheight: 999
};
},
ready: function(){
this.myheight = this.offsetHeight;
}
});
同样,它不起作用 - 它不输出任何内容 - 我在控制台中没有收到任何错误或警告。
然后,我认为this 可能不是 HTMLElement,所以我搜索了 Vue 文档,发现所有 Vue 实例都应该有一个指向 HTMLElement 的$el 属性——或者至少我是这么理解的它...所以我尝试在上面的两个示例中使用this.$el.offsetHeight,但同样没有成功。
有人能指出我正确的方向吗?感谢所有帮助...
【问题讨论】:
标签: javascript vue.js