【问题标题】:How Do I Get The offsetHeight of a Component Element in Vue.js?如何在 Vue.js 中获取组件元素的 offsetHeight?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 完全正确 - 我知道这很明显!谢谢!
    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 2015-09-13
    • 2019-09-14
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2021-06-06
    相关资源
    最近更新 更多