element-plus默认就支持黑白色主题,因此要实现主题切换只需要引入相关css文件,然后在html上添加上名为dark的类就完成了
文档:https://element-plus.org/zh-CN/guide/theming.html
为了方便切换主题,这里使用vueuse的useDark方法,此方法会给html增加相关的class
引入黑色主题
main.js中引入黑色版css变量文件:
import 'element-plus/dist/index.css'
// 黑色主题变量
import 'element-plus/theme-chalk/dark/css-vars.css'
安装VueUse
VueUse是Vue3组合式API的工具集合,提供很多工具方便开发自己的组件等。
安装:npm i @vueuse/core
切换主题
在useGlobalConfigStore中定义isDarkTheme的变量:
const isDarkTheme = useDark()
changeTheme (dark) {
isDarkTheme.value = dark
}
页面上切换主题:
globalConfigStore.changeTheme(!globalConfigStore.isDarkTheme)
最终开源地址: