我正在使用Vue创建一个组件.js,并将其插入DOM中,没有任何问题.一旦元素进入DOM,我想知道它的渲染高度——也就是说,我想得到它的offsetHeight.我想不出怎么做——我肯定错过了一些非常明显的东西.这就是我try 过的:

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' });

但它不起作用——《我的身高》最后是空的.我认为问题可能在于,它可能在被插入DOM之前试图生成计算(computed)属性,所以我没有使用计算(computed)属性,而是try 了以下方法:

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

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

然后,我认为也许this不是HTMLElement,所以我搜索了Vue文档,发现所有Vue实例都应该有一个指向HTMLElement的$el属性——或者至少我是这样理解的...所以我try 在上面两个例子中使用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' });

Vue.js相关问答推荐

如何将$validator实例注入到使用组合API语法的Vue2.7应用程序中

如何将外部 svg 转换为 Vue3 组件?

在 VueJS 中,将变量而不是组件的字符串名称传递给动态组件的 :is 属性不起作用

作为props 传递的原始 ref 的 Vue 3 react 性

JSDoc 单文件 Vue 组件

如何使用 vue.js 和 vue 路由实现当前路由的子菜单的子菜单

在 Vue 项目之间共享assets和组件

使用 vue-cli 遇到无法推断解析器错误

如何为 Vue 应用提供 robots.txt

根据 URL 有条件地隐藏视图组件

如何为 Vue 项目设置 lint-staged?

导入没有 .vue 扩展名的 *.vue 文件时出现以下错误?

如何使用 vuejs 从 SPA 访问 /storage -laravel- 中的图像

Vue 3 - 带有全局组件的无法解析组件

NuxtServerInit 在 Vuex 模块模式下不起作用 - Nuxt.js

Vuetify - 如何在 v-data-table 中单击时突出显示行

为什么 vue 文档说 refs 不是响应式的,而实际上它们是响应式的

如何使用 VueJS / Typescript 导入 JSON 文件?

使用 refs 聚焦元素目标

Vue.js 显示空格(换行符)