《vue》在 <style> 中使用 js 变量

有时候我们需要在样式中使用来自 js 的变量

比如: 想要屏幕的高度,当然你可以用100vh,但是这是个相对单位,有时候我想获取绝对单位px;

还有其他的很多情况,需要动态计算的,当然很多情况也可以动态绑定style解决。

<div :style="{height: docHeight}"></div>

方法:

App.vuemounted生命周期中(这种情况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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。