vue + css3 实现主题色切换


开发商城总免不了主题色的更换, 总不能一个个颜色手动粘贴复制吧,一键切换不香嘛

首先需要用到css3的var()函数,用法如下

1 body {
2     --size: 20px;
3     font-size: var(--size);    // 20px
4     padding:var(--size);       // 20px
5 }

 

思路:

  • 就是在vue的最外层盒子app中添加主题色的色值, 需要用到主题色的地方皆用变量取值

 

上代码:

app.vue中

 1 <template>
 2   <div id="app" :style="appStyle">
 3     <router-view class="app" ></router-view>
 4   </div>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   name: "app",
10 
11   computed: {
12     appStyle(){
13       const themeColor = 1 
14 
15       // console.log('[App路由启动函数]', props, context, router)
16       const themeColors = [
17         '',
18         '#DA251D',
19         '#f56fa6',
20         '#ff605c',
21         '#86b902',
22         '#40baff',
23       ]
24       return `--theme: ${themeColors[themeColor]}`
25     }
26   },
27 
28 };
29 </script>
30 
31 <style lang="scss" rel="stylesheet/scss">
32 @import "assets/style/index.scss";
33 
34 #app {
35   height: 100%;
36   width: 100%;
37   .app {
38     background: #f5f5f5;
39     padding-top: 45px;
40   }
41 }
42 </style>

通过更改 themeColor 的数值作为 themeColors 数组的索引值来进行更换色值

 

需要用到的地方, 用以下写法即可

1 background-color: var(--theme);
2 color: var(--theme);

 

效果图

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM