如何在 SCSS 中使用 JavaScript 中的变量

JS中实例:

  • 在 JavaScript 中声明了一个名为 theme 的变量,并赋予了一个字符串值
<script setup>
    const theme = '#f03d3d';
</script>

HTML中实例:

  • 接下来,在 Vue 组件的模板中的 <div> 元素上使用了 :style 属性,并通过对象语法将 --theme 自定义属性与 theme 变量绑定在一起,例如 :style="{'--theme': theme}"。这样就将 theme 的值传递给了组件的样式中。
<template>
    <div class="container" :style="{'--theme': theme}"></div>
</template>

在scss中使用变量:

  • 在组件的样式中,可以使用 var(--theme) 来引用 --theme 自定义属性的值。例如,可以在 SCSS 样式中使用 background 属性,通过插值语法 #{'var(--theme)'} 将 --theme 自定义属性的值动态插入到渐变背景中,例如 background: linear-gradient(180deg, #{'var(--theme)'} 0%, rgba(48, 75, 204, 0) 95%);
<style lang="scss" scoped>
    //样例1
    .container {
      $theme: var(--theme);
      background: linear-gradient(180deg, #{$theme} 0%, rgba(48, 75, 204, 0) 95%);
    }

    //样例2
    .container {
      background: linear-gradient(180deg, #{'var(--theme)'} 0%, rgba(48, 75, 204, 0) 95%);
    }
</style>

猜你喜欢

转载自blog.csdn.net/weixin_39273589/article/details/132068467