文章大綱
element plus這幾個月改動幅度滿大的,之前寫的文章舊版本有些方式已經不能使用了。
新版本這次我下載了:1.1.0-beta.24
,自訂主題的方式這邊再重新整理一次。
下載Element plus
新版官網從這裡進去,選上面的Guide
–> Installation
這邊我使用的是yarn
:
$ yarn add element-plus
在scss資料夾中新增兩個檔案:main.scss
、element-variables.scss
為什麼要新增兩個檔案呢?因為我習慣把所有scss引用到main.scss
裡面,然後main.js
只要引入main.scss
就好。
而element-variabled.scss
才是真正我們設定主題的地方,所以你直接只新增element-variables.scss
也是可以的。
@import "./element-variables";
先從原官網的文件複製element-variables.scss
的內容並且貼上:
@forward "element-plus/theme-chalk/src/common/var.scss
" with (
$colors: (
"primary": (
"base": #745847,
),
),
);
@import "element-plus/theme-chalk/src/index.scss";
然後你yarn serve
的時候會發現他有錯誤:
These relative modules were not found:
./fonts/element-icons.ttf in ./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-3-1!./node_modules/postcss-loader/src??ref--8-oneOf-3-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-3-3!./src/scss/main.scss
./fonts/element-icons.woff in ./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-3-1!./node_modules/postcss-loader/src??ref--8-oneOf-3-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-3-3!./src/scss/main.scss
因為他找不到字型檔案,我們手動把字型檔案加上去:
@forward "element-plus/theme-chalk/src/common/var.scss" with (
$colors: (
"primary": (
"base": #745847,
),
),
$font-path: "~element-plus/dist/fonts" //加上這行
);
@import "element-plus/theme-chalk/src/index.scss";
這時候再隨便一頁放上按鈕,設定主色就可以看到成功了。
<el-button type="primary">Hello</el-button>
如果是要在其他的scss中引用element plus的顏色變數要怎麼使用呢?
從你本地的node_moduels
中找到element-plus/theme-chalk/src/mixin/_var.scss
去裡面查看css root variables的命名規則,
@mixin set-css-color-type($type) {
--el-color-#{$type}: #{map.get($colors, $type, 'base')};
//...
}
@mixin set-css-var-type($name, $type, $variables) {
--el-#{$name}-#{$type}: #{map.get($variables, $type)};
}
再去element-plus/theme-chalk/src/common/var.scss
看參數schema,
//主要顏色
$colors: map.deep-merge(
(
'white': #ffffff,
'black': #000000,
'primary': (
'base': #409eff,
),
'success': (
'base': #67c23a,
),
'warning': (
'base': #e6a23c,
),
'danger': (
'base': #f56c6c,
),
'error': (
'base': #f56c6c,
),
'info': (
'base': #909399,
),
),
$colors
);
//文字顏色
$text-color: map.merge(
(
'primary': #303133,
'regular': #606266,
'secondary': #909399,
'placeholder': #c0c4cc,
),
$text-color
);
然後看element-plus/theme-chalk/src/var.scss
跑的function:
// --el-color-#{$type}
// --el-color-#{$type}-light-{$i}
@each $type in (success, warning, danger, error, info) {
@include set-css-color-type($type);
}
// --el-text-color-#{$type}
@each $type in (primary, regular, secondary, placeholder) {
@include set-css-var-type('text-color', $type, $text-color);
}
經過縝密的計算與謹慎的判斷,呼叫變數就是:
div {
background-color: var(--el-color-primary);
}
h3 {
color: var(--el-text-color-regular);
}
當然,這個前提是你最前面有引用element-variables.scss
。
發表評論
想要加入討論嗎?請盡情發表您的想法!