有时候我们需要在样式中使用来自 js 的变量
比如: 想要屏幕的高度,当然你可以用100vh
,但是这是个相对单位,有时候我想获取绝对单位px
;
还有其他的很多情况,需要动态计算的,当然很多情况也可以动态绑定style
解决。
<div :style="{height: docHeight}"></div>
方法:
在App.vue
的mounted
生命周期中(这种情况main.js)中也行:
// const body = document.querySelector('body');
const body = document.querySelector('#app');
const docHeight = document.body.clientHeight;
body && body.style.setProperty('--docHeight', docHeight + 'px');
使用
/* CompA.vue */
.comp-a-wrap {
height: var(--docHeight);
}
利用scss:
$docHeight: var(--docHeight);
使用:
// CompA.vue
.comp-a-wrap {
height: $docHeight
}