简体   繁体   English

数据未在样式绑定(Vue)中更新

[英]Data not updating in style binding (Vue)

I'm trying to reactively set the height of a wrapper div using data in Vue. 我正在尝试使用Vue中的数据来反应性地设置包装div的高度。 The data is set when all the children of the wrapper div is loaded and is then set to the totalt height of all of them added together. 当包装器div的所有子代均加载时设置数据,然后将其设置为所有加在一起的总高度。 Basically I want the wrapper to have a fixed pixel value in CSS based on the height of all of its children combined. 基本上,我希望包装器在CSS中基于其所有子级的总高度合并一个固定的像素值。

I use watch to set the height after the content from the database has been loaded. 在装入数据库中的内容之后,我使用watch来设置高度。 post in the code below is the array from the database that contains the data of the post that the current component should render from. 以下代码中的post是数据库中的数组,其中包含当前组件应从中渲染的post数据。

watch: {
        post(){
            this.$nextTick(() => {
                this.setTotalHeight();
            })
        }
    }

The setTotalHeight() method looks like this: setTotalHeight()方法如下所示:

setTotalHeight() {
            this.totalHeight = this.$refs.top.offsetHeight + this.$refs.middle.offsetHeight + this.$refs.bottom.offsetHeight
        }

I also trigger the setTotalHeight() method on resize. 我还会在调整大小时触发setTotalHeight()方法。

When these functions has run, the totalHeight data value is set to the number that the calculation in setTotalHeight() equals to. 运行这些函数后, totalHeight数据值将设置为setTotalHeight()中的计算所等于的数字。 I can see the value if I look in the dev tools, and if I output the value with {{totalHeight}} in the "DOM", I can see it with the correct value. 如果查看开发工具,就可以看到该值;如果在“ DOM”中以{{totalHeight}}输出该值,则可以看到正确的值。

However, when I try to apply this value to the wrapper div by doing :style="{height: totalHeight}" , it's not updating. 但是,当我尝试通过:style="{height: totalHeight}"将此值应用于包装div时,它没有更新。 I initially set the totalHeight data value to 0 , and this is what the style is being set to without ever changing. 我最初将totalHeight数据值设置为0 ,这就是样式设置为不变的方式。

Am I doing something wrong with this or why is the style binding not updating when the data itself is updating and the output in the "DOM" with {{totalHeight}} is updating accordingly? 我这样做有问题吗?为什么当数据本身正在更新并且带有{{totalHeight}}的“ DOM”中的输出也相应地更新时,样式绑定仍未更新? Is style binding not reactive or what might be causing this? 样式绑定不是被动的,还是可能导致这种情况?

Did you add 'px' to your height value? 您是否在身高值上加上了“ px”? If not, try this: 如果没有,请尝试以下操作:

:style="{height:totalHeight+'px'}" 

Its just like you are setting a CSS height proprety with no unit height : 1000 就像您要设置CSS高度属性,而没有单位height : 1000

you need to add the unit after the height on the style binding ( px / em ...etc) like: 您需要在样式绑定的高度( px / em ... etc)的高度后添加单位,例如:

<wrapper :style="{height: totalHeight +'px'}" </wrapper> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM