通过添加大小调整事件侦听器来更新DOM元素的高度

时间:2019-06-01 16:16:34

标签: vue.js

我想确保我的组件的高度和宽度相同。为此,我添加了 resize 事件监听器。目前我有此代码

<template>
    <div
        :ref="cellId"
    >
    </div>
</template>

<script>
export default {
    data: function() {
        return {
            cellId: '_' + Math.random().toString(36).substr(2, 9)
        };
    },
    methods: {
        updateCellHeight: function() {
            this.$refs[this.cellId].clientHeight = this.$refs[this.cellId].clientWidth;
        }
    },
    created: function() {
        window.addEventListener("resize", this.updateCellHeight);
        this.updateCellHeight();
    },
    destroyed: function() {
        window.removeEventListener("resize", this.updateCellHeight);
    }
}
</script>

所以我要做的就是生成一个唯一的ID,以访问Vue实例中的DOM元素。此外,我运行事件并将高度设置为等于宽度。

通过循环并调整窗口大小创建多个组件时,出现此错误

  

未捕获的TypeError:无法分配为只读属性'clientHeight'   对象“#”的       在VueComponent.updateCellHeight

如何访问HTML元素并确保其高度等于其宽度?

1 个答案:

答案 0 :(得分:3)

由于错误消息试图告诉您, tooltip(batch: Batch) => { batch.name } 是只读属性。您可能需要修改<div *ngFor="let batch in batches"> <div class="tooltip">{{tooltip(batch)}}</div> </div> 属性,但请记住clientHeight包含填充。尝试使用Window.getComputedStyle()获取元素样式并从此处获取宽度。

但是,您实际上可以完全不使用任何JS来实现此目的:http://www.mademyday.de/css-height-equals-width-with-pure-css.html