首页 > 解决方案 > 如何在 Vue JS 中设置动态样式属性

问题描述

我正在尝试将元素的最小高度设置为.vue页面。style 属性绑定到styleObject

    <b-container class="mt-3" v-bind:style="styleObject">

我在我的脚本中使用 mount 来设置 styleObject。

    export default {
      data: function() {
        containerHeight: null,
        styleObject: {
          minHeight: this.containerHeight
        }
      },
      mounted() {

        let headerHeight = document.querySelector('#header').offsetHeight; 
        let navHeight = document.querySelector('#main-menu').offsetHeight; 
        let footerHeight = document.querySelector('#footer').offsetHeight; 

        let ht = screen.height - (headerHeight + navHeight + footerHeight);

        alert(ht);//the calculated height is displayed

        this.containerHeight = ht + "px";
      }
    }

容器高度不调整

标签: javascriptvue.js

解决方案


当您声明它们时,不应将其他数据道具用作另一个数据道具的值,因为它们不会是反应性的。

避免:

styleObject: {
      minHeight: this.containerHeight
    }

只需将其设置为 null 并执行

styleObject: {
      minHeight: null
    }
this.styleObject.minHeight = ht + "px";

推荐阅读