标题重写为:Vue中添加内联样式的CSS变量
P粉421119778
P粉421119778 2023-12-31 12:51:41
0
1
472

我在组件中使用 css 变量,并根据 setup() 中计算的数据设置 div 的宽度

setup(props) {
    const progressBar = PositionService.getProgressBar(props.position);
    const progressWidth = `${progressBar}%`;

    ...
    return { ..., progressWidth };
}

然后我使用这个变量作为 css 变量。

<style lang="scss" scoped>
.progress-bar-width {
  --progress-bar-width: v-bind("progressWidth");
  width: var(--progress-bar-width);
}
</style>

渲染页面时,我注意到内联样式被添加到 html 父组件中,从而导致

<a href="#/1070/applications/status/1" class="card position-relative border-gray-300 border-hover overflow-hidden h-500px" data-v-61475b35="" style="--61475b35-progressWidth:43.0613%;">.....</a>

CSP 阻止内联样式,因此此方法不起作用。 如何在没有内联样式的情况下使用 css 变量?

P粉421119778
P粉421119778

全部回复(1)
P粉576184933

这是一个黑客解决方案,但由于没有内联样式,这是我唯一能想到的:

向您的模板添加“样式”组件。这将被 DOM 中的 标签替换。在组件内部将所需的 CSS 变量添加到 :root

<component :is="`style`">
    :root { --progress-bar-width: {{ progressWidth }}; }
</component>
<div class="progress-bar-width"></div>
<style lang="scss" scoped>
.progress-bar-width {
  width: var(--progress-bar-width);
}
</style>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!