如何获取Vue.js中组件元素的offsetHeight?

How Do I Get The offsetHeight of a Component Element in Vue.js?

我正在使用 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 不是一个 HTML 元素,所以我搜索了 Vue 文档,发现所有 Vue 实例都应该有一个 $el 属性 指向 HTMLElement - 或者至少我是这样理解的...所以我尝试在上面的两个示例中使用 this.$el.offsetHeight,但再次没有成功。

有人能指出我正确的方向吗?感谢所有帮助...

看来问题出在您的模板上。您似乎有一个 fragment instance,这意味着您没有围绕所有子项的顶级元素。

所以不是这个,$el 可能不是指你想要的东西......

<!-- component template -->
<template id="my-component">
    <h1>Hello World</h1>
    <p>Lorem ipsum dolor sit amet.</h1>
    <pre>{{ myheight }}</pre>
</template>

…您可以将您的组件包装在父元素中:

<!-- component template -->
<template id="my-component">
    <div class="my-component">
        <h1>Hello World</h1>
        <p>Lorem ipsum dolor sit amet.</p> <!-- and close the tag correctly -->
        <pre>{{ myheight }}</pre>
    </div>
</template>

然后你可以使用this.$el.offsetHeight获得偏移高度:

Vue.component('my-component',{
    template: '#my-component',
    data: function(){
        return {
            myheight: 999
        };
    },
    ready: function(){
        this.myheight = this.$el.offsetHeight;
    }
});

new Vue({ el: '#my-component' });