scss中检测变量需区分声明与赋值:variable-exists()仅判断是否声明,meta.type-of($var) == 'null'才精准识别null;空值应包裹@if避免输出无效css;map-has-key()配合map-get()安全处理配置map;@extend不支持条件逻辑,应改用@mixin。

SCSS 中用 @if 检测变量是否定义或非空
SCSS 本身不支持运行时检测“某个 CSS 属性是否存在”,但开发中常需根据某个配置变量(如 $border-radius、$shadow)是否被赋值或是否为 null/''/false,来决定是否生成对应样式。核心靠 @if + variable-exists() 或 not (false == $var) 等判断。
注意:variable-exists() 只能检测变量是否**声明过**,不能判断是否为 null;而 meta.type-of($var) == 'null' 才能真正识别未赋值或显式设为 null 的情况。
-
variable-exists(border-radius)→ 检查$border-radius是否声明(哪怕值是null,也返回true) -
meta.type-of($border-radius) == 'null'→ 精确判断是否为null -
$border-radius != null and $border-radius != ''→ 常用兜底写法,兼容字符串空值
生成带条件的 CSS 属性:避免输出无效声明
直接写 border-radius: $border-radius; 会导致编译出 border-radius: null;(浏览器忽略),但污染 CSS 输出且影响可读性。应包裹在 @if 中,只在有值时输出。
@mixin button-style($border-radius: null, $shadow: null) {
@if $border-radius != null and $border-radius != '' {
border-radius: $border-radius;
}
@if $shadow != null and $shadow != '' {
box-shadow: $shadow;
}
}
这个写法能干净地跳过空值,但要注意:SCSS 对 0、0px、transparent 等合法值也会被 != '' 判为真,所以不要误加 and $border-radius != '' 到数字型变量上——除非你明确想排除空字符串输入。
用 map-has-key() 处理配置对象中的属性开关
当样式逻辑基于一个配置 map(如 $button-config: ('radius': 4px, 'hover-shadow': true)),需检测某个 key 是否存在且启用,此时 map-has-key() 比 @if $map.radius 更安全——后者在 key 不存在时会报错。
-
map-has-key($button-config, 'radius')→ 安全判断 key 是否存在 -
map-get($button-config, 'radius')→ 获取值,若 key 不存在返回null - 组合使用:
@if map-has-key($button-config, 'radius') and map-get($button-config, 'radius') != null
这样既防报错,又避免把 map-get 的 null 当作有效值传给属性。
慎用 @extend 配合条件逻辑:它不支持动态分支
别试图在 @if 块里写 @extend .btn-base;——SCSS 编译期就解析 @extend,无法延迟到条件成立时才继承。如果需要“有条件地复用样式”,改用 @include 混入更可靠。
例如下面写法是错的:
@if $use-base-style {
@extend .btn-base; // ❌ 编译失败或行为不可控
}
正确做法是把基础样式封装进 mixin:
@mixin btn-base {
padding: 8px 16px;
font-weight: 500;
}
@if $use-base-style {
@include btn-base; // ✅ 安全、可嵌套、可条件调用
}
复杂组件中容易忽略这点,结果发现样式没继承、或者整个文件编译报错,根源往往在这里。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











