Svelte SMUI中如何从SCSS获取主题色到JavaScript?
在Svelte+SMUI中处理SCSS主题变量并传递到JavaScript
一、先解决CSS变量--mdc-theme-primary不生效的问题
SMUI依赖Material Design主题变量,但默认@material/theme不会自动将SCSS变量转换为全局CSS自定义属性,需要手动输出:
@use 'sass:color'; @use '@material/theme/color-palette'; @use '@material/theme/index' as theme with ( $primary: #ef8611, $secondary: color.scale(#8aace1, $lightness: 90%), $surface: #333, $background: #fff, $error: color-palette.$red-900 ); // 将SCSS主题变量输出为全局CSS自定义属性 :root { --mdc-theme-primary: theme.$primary; --mdc-theme-secondary: theme.$secondary; --mdc-theme-surface: theme.$surface; --mdc-theme-background: theme.$background; --mdc-theme-error: theme.$error; }
将这段代码放在全局样式文件(比如src/app.scss)中,再在根布局组件(src/routes/+layout.svelte)里导入,确保所有组件都能访问这些变量。
二、将SCSS中的$primary获取到JavaScript的可行方法
方法1:通过CSS自定义属性获取(推荐)
借助已生成的全局CSS变量,在Svelte组件中用getComputedStyle读取:
<script> import { onMount } from 'svelte'; let primaryColor; onMount(() => { const root = document.documentElement; // 获取并去除首尾空格 primaryColor = getComputedStyle(root).getPropertyValue('--mdc-theme-primary').trim(); console.log(primaryColor); // 输出 #ef8611 }); </script>
方法2:通过SCSS的:export导出给JS
在主题SCSS文件中添加:export块,将SCSS变量直接导出为JS可导入的对象:
// theme-vars.scss @use 'sass:color'; @use '@material/theme/color-palette'; @use '@material/theme/index' as theme with ( $primary: #ef8611, $secondary: color.scale(#8aace1, $lightness: 90%), $surface: #333, $background: #fff, $error: color-palette.$red-900 ); // 输出全局CSS变量 :root { --mdc-theme-primary: theme.$primary; // 其他变量同理 } // 导出变量给JS使用 :export { primary: theme.$primary; secondary: theme.$secondary; surface: theme.$surface; }
然后在Svelte组件中直接导入使用:
<script> import themeVars from './theme-vars.scss'; console.log(themeVars.primary); // 直接获取 #ef8611 </script>
这种方式需要你的构建工具(如Vite、SvelteKit)支持SCSS导出,默认情况下这些工具都已配置好。
不推荐的方法:重复定义颜色值
直接在JS中写和SCSS一致的#ef8611,但后续修改主题时需要同步修改SCSS和JS两处,容易出错,不建议使用。
内容的提问来源于stack exchange,提问作者vinalti
相关产品推荐
相关产品推荐

