【问题标题】:How can I access SCSS colors vars in a Vue template's javascript?如何在 Vue 模板的 javascript 中访问 SCSS 颜色变量?
【发布时间】:2021-02-28 15:27:00
【问题描述】:

在我的应用程序中,我有一个组件通知。我通过 mixin 方法toast('message to display', 'color-variable') 调用其他组件中的通知。我想要实现的是我的通知组件具有“颜色变量”的背景颜色。问题是颜色变量是在 scss 文件中设置的。从 scss 代码中,我可以使用函数 color('color-name') 获取它们,但是,我不知道如何从我的 vue 模板的 javascript 中动态使用该 scss 函数。

我试图通过:style="{'background-color': color(${notification.status})}" 来实现这一点,但它不起作用。有没有办法在视图模板中访问 scss vars 作为数据?

【问题讨论】:

  • 只需为此颜色创建实用程序类并在组件中使用此类。您可以通过 sass 文件中的 for 循环和 .bg-color--red 等颜色的 crate 类来做到这一点。然后您可以在组件中使用此类。
  • sass 已预编译为 css,因此在您的应用中,您无法访问此变量和函数,因为 css 上不存在它们

标签: javascript vue.js sass


【解决方案1】:

您可以将 sass 变量导出到您的 vue.js 应用程序中。我发现这对主题变量特别有效。以下是我在其中一个应用程序中设置的颜色变量示例:

$primaryShades: (
  50: #f5fef9,
  100: #e6fcf1,
  200: #d5fae8,
  300: #c4f8df,
  400: #b8f7d8,
  500: #abf5d1,
  600: #a4f4cc,
  700: #9af2c6,
  800: #91f0c0,
  900: #80eeb5,
  A100: #fff,
  A200: #fff,
  A400: #fff,
  A700: #f6fffa
);

$primary: map-get($primaryShades, 500);

$primary_100: map-get($primaryShades, 100);
$primary_200: map-get($primaryShades, 200);
$primary_300: map-get($primaryShades, 300);
$primary_400: map-get($primaryShades, 400);
$primary_500: map-get($primaryShades, 500);
$primary_600: map-get($primaryShades, 600);
$primary_700: map-get($primaryShades, 700);
$primary_800: map-get($primaryShades, 800);
$primary_900: map-get($primaryShades, 900);


$error: #ef9a9a;

$success: #76c078;

/* stylelint-disable -- exports for js don't need/want style rules applied to this block. */
:export {
  primary: $primary;
  error: $error;
  success: $success;
}

@each $color, $value in $primaryShades {
  :export {
    primary#{$color}: $value;
  }
}

/* stylelint-enable */

然后,如果您想要全局访问,您可以通过全局 mixin 将它们导入到您的应用中:

import colors from './assets/scss/colors_vars.scss';// edit for your location

// in some global mixin
Vue.mixin({
  data() {
    return {
      colors: colors
    };
  }
})

最终在您的代码中访问它们,就像您访问任何其他数据位一样:

toast('message to display', this.colors.error) // in this example I am applying the error color

因此,您可以编写所需的任何逻辑,以便在需要时生成正确的颜色。

computed: {
   notificationColor() {
     if(errorCondition) {
      return this.color.error
    }
     if(successCondition) {
      return this.color.success
    }
  }
}

如果您定义了颜色数组,您可以使用 scss 块查看如何循环它们并导出。以访问主阴影 50 为例,this.colors.primary50。因此,您可以在样式中保留颜色设置,但可以在 js 中无缝使用它们并在一处更改它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-31
    • 2018-05-31
    • 2020-02-17
    • 2014-04-08
    • 2015-12-04
    • 2014-12-21
    • 2021-12-11
    • 2020-12-23
    相关资源
    最近更新 更多