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

11

我正在使用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,但同样没有成功。

有人能指点我正确的方向吗?非常感谢所有的协助...

1个回答

8
看起来问题出在你的模板上。你似乎有一个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' });

完全正确 - 我知道这一定是显而易见的事情!谢谢你! - Lux Logica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接