【问题标题】:get element style and assign it to another element in vue.js获取元素样式并将其分配给 vue.js 中的另一个元素
【发布时间】:2026-02-17 22:30:03
【问题描述】:

我正在使用 VUE.js 2

这是我的 DOM:

<aside :style="{height : height()}" class="col-sm-4 col-md-3 col-lg-3">...</aside>

<main class="col-sm-8 col-md-9 col-lg-9" ref="userPanelMainContents">...</main>

这是我的脚本:

export default {
    data() {
        return {}
    },
    methods: {
        height () {
            return this.$refs.userPanelMainContents ? this.$refs.userPanelMainContents.offsetHeight + 'px' : '0px'
        }
    }
}

我想获取 userPanelMainContents 高度并将其分配给旁边的标签。 我该怎么做?!!!

【问题讨论】:

    标签: javascript jquery html css vue.js


    【解决方案1】:

    尝试返回一个数据属性而不是使用返回高度的方法,然后你可以使用mounted函数设置高度。

    像这样:

    <aside :style="{ height: height }" class="col-sm-4 col-md-3 col-lg-3">...</aside>
    
    <main class="col-sm-8 col-md-9 col-lg-9" ref="userPanelMainContents">...</main>
    
    
    export default {
        data() {
            return {
                height: '0px'
            }
        },
        mounted () {
            this.height = this.$refs.userPanelMainContents[0].style.height;
        }
    }
    

    已编辑:将计算属性更改为数据属性,并在调用挂载事件时设置它。

    它将使用不同的语法,因为我不能在 codepen 上使用 .vue 文件,但这里是工作代码。

    https://codepen.io/michael_coder/pen/qXbxXW

    【讨论】:

    • 渲染函数中的错误:“TypeError:无法读取未定义的属性'userPanelMainContents'”
    • 我会为你编辑和修复它。我认为正在发生的事情是在计算之后创建了参考。
    • 我使用 *.vue 文件和 webpack。这种结构有可能造成这种情况吗?
    • 全部编译到 es2015。这不应该导致问题。我一直在使用 *.vue 和 webpack。
    • 不幸的是没有字!!
    最近更新 更多