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

Lux*_*ica 10 javascript 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>
Run Code Online (Sandbox Code Playgroud)

Vue Javascript:

Vue.component('my-component',{
    template: '#my-component',
    computed: {
        myheight: function(){
            return this.offsetHeight;
        }
    }
});

Vue({ el: '#my-app' });
Run Code Online (Sandbox Code Playgroud)

但它不起作用 - 'myheight'最终为空.我认为可能问题是它可能在插入到DOM之前尝试生成计算属性,因此我尝试使用计算属性而不是:

Vue.component('my-component',{
    template: '#my-component',
    data: function(){
        return {
            myheight: 999
        };
    },
    ready: function(){
        this.myheight = this.offsetHeight;
    }
});
Run Code Online (Sandbox Code Playgroud)

同样,它不起作用 - 它什么都不输出 - 我在控制台中没有收到任何错误或警告.

于是,我想,也许this不是一个HTML元素,所以我搜索了Vue的文档,发现所有Vue的情况下应该有一个$el指向HTML元素属性-或者至少这是我了解它的方式......所以我试着用this.$el.offsetHeight在以上两个例子,但都没有成功.

有人能指出我正确的方向吗?所有的帮助表示赞赏......

nil*_*ils 6

看起来问题出在您的模板中.您似乎有一个片段实例,这意味着您没有包围所有子项的顶级元素.

所以不是这样,在哪里$el可能没有提到你想要的......

<!-- component template -->
<template id="my-component">
    <h1>Hello World</h1>
    <p>Lorem ipsum dolor sit amet.</h1>
    <pre>{{ myheight }}</pre>
</template>
Run Code Online (Sandbox Code Playgroud)

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

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

然后你可以使用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' });
Run Code Online (Sandbox Code Playgroud)