此功能仅是告知方法,写的过于粗糙,关键在于第三、四、五步,具体的哪些元素的主题需要变更,根据你的项目而定,例如nav背景色、图标颜色、button背景色等元素,
具体的样式自己完成即可,样式最好使用变量的形式,为了直观,我就直接更改的,建议使用css变量的形式,事先定义好各个主题的色值,直接引入即可
1、在navbar中写好换肤的HTML和对应的点击事件,并把改成颜色作为参数传过去
2、我这里使用的是elementUI的<el-dropdown>
<el-dropdown trigger="hover" type="primary"> <el-dropdown-menu slot="dropdown"> <el-dropdown-item @click.native="changeColor('red')"><span class="icon iconfont icongerenzhongxin" />red</el-dropdown-item > <el-dropdown-item @click.native="changeColor('yellow')"><span class="icon iconfont iconxiugaimima" />yellow</el-dropdown-item > <el-dropdown-item @click.native="changeColor('green')"><span class="icon iconfont iconxiugaimima" />gren</el-dropdown-item > <el-dropdown-item @click.native="changeColor('blue')"><span class="icon iconfont icontuichu" />blue</el-dropdown-item > </el-dropdown-menu > </el-dropdown >
3、然后是换肤的点击事件的函数
// 换肤 changeColor (color) { console.log('颜色值', color) window.document.documentElement.setAttribute('data-theme', color) localStorage.setItem('theme', color) },
4、在main.js中最后边添加判断,如果有值,则用,没有值则赋值为默认色
let theme = localStorage.getItem('theme') console.log('主题色值', theme) if (!theme) { theme = 'default' } window.document.documentElement.setAttribute('data-theme', theme)
5、最后一步,在引入的样式中定义各种主题色
6、最后的结果展示