Vue+scss白天和夜间模式切换功能的实现方法__Vue.js
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
图片被压缩了不够清晰。
- 安装Scss
注:若安装失败可以考虑使用cnpm,或者切换npm源等方式安装。
npm install node-sass --save-dev //安装node-sass
npm install sass-loader --save-dev //安装sass-loader
npm install style-loader --save-dev //安装style-loader
- 新建页面DarkModelPage.vue
文件所在位置:src/DarkModelPage.vue
命名路由路径:/dark-model-page
<template>
<div id="DarkModelPage">
</div>
</template>
<script>
export default {
}
</script>
<style scoped lang="scss">
</style>
-
在src/assets新建目录scss
-
在src/assets/scss新建目录common
-
然后需要新建三个scss文件分别是
_themes.scss
_handle.scss
common.scss
- _themes.scss
$themes: (
light: (
background_color: #cccccc,//背景色
text-color: rgba(0, 0, 0, 0.65), // 主文本色
),
dark: (
background_color: #181c27,//背景
text-color: rgba(255, 255, 255, 0.65), // 主文本色
)
);
- _handle.scss
@import "./_themes.scss";
//遍历主题map
@mixin themeify {
@each $theme-name, $theme-map in $themes {
//!global 把局部变量强升为全局变量
$theme-map: $theme-map !global;
//判断html的data-theme的属性值 #{}是sass的插值表达式
//& sass嵌套里的父容器标识 @content是混合器插槽,像vue的slot
[data-theme="#{$theme-name}"] & {
@content;
}
}
}
//声明一个根据Key获取颜色的function
@function themed($key) {
@return map-get($theme-map, $key);
}
//获取背景颜色
@mixin background_color($color) {
@include themeify {
background: themed($color)!important;
}
}
//获取字体颜色
@mixin font_color($color) {
@include themeify {
color: themed($color)!important;
}
}
- common.scss
@import "@/assets/scss/common/_handle.scss";
/**
自定义的公共样式...
**/
- DarkModelPage.vue中使用
<template>
<div id="DarkModelPage">
<div>
<h1 class="title">天小天个人网</h1>
<a class="btn" @click="modelBrn">模式切换</a>
</div>
</div>
</template>
<script>
export default {
name: "DarkModelPage",
data(){
return {
dark:false,
}
},
methods:{
modelBrn(){
this.dark = !this.dark;
if(this.dark){
window.document.documentElement.setAttribute( "data-theme", 'dark' );
}else{
window.document.documentElement.setAttribute( "data-theme", 'light' );
}
},
},
mounted() {
window.document.documentElement.setAttribute( "data-theme", 'light' );
},
}
</script>
<style scoped lang="scss">
@import '@/assets/scss/common/common';
#DarkModelPage{
//在此使用了背景颜色变量
@include background_color("background_color");
//再次使用了文字颜色变量
@include font_color("text-color");
width: 100vw;
height: 100vh;
display: flex;
justify-content:center;
align-items: center;
transition: background 1s , color 0.6s;
.title{
margin-bottom: 20px;
}
.btn{
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 40px;
margin: 0 auto;
}
}
</style>
- 注:如需更多颜色及样式切换,只需要在_themes.scss设置好变量,通过 _handle.scss设置切换函数,即可以在页面中通过该函数对指定样式进行设置。
本文演示视频:点击浏览
更多前端内容欢迎关注公众号:天小天个人网
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 天小天 原文链接:https://juejin.im/post/6913734532206166023