安装Element-plus:
# NPM
$ npm install element-plus --save
# Yarn
$ yarn add element-plus
# pnpm
$ pnpm install element-plus
在 mian.ts 中引入Element-plus:
main.ts 引入element-ui
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
darkLight.vue子组件:
<template>
<div>
<el-switch
v-model="theme"
inline-prompt
:active-icon="Sunny"
:inactive-icon="Moon"
style="--el-switch-on-color: #ff0000; --el-switch-off-color: #409eff"
@change="toggleDark()"
/>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import { Moon, Sunny } from "@element-plus/icons-vue";
import { useDark, useToggle, useStorage } from "@vueuse/core";
const isDark = ref(useDark());
const toggleDark = useToggle(isDark);
// 切换按钮 localStorage 中的值,保证刷新不重置
const vueuseColorScheme = useStorage("vueuse-color-scheme", null);
const theme = vueuseColorScheme.value === "auto" ? ref(false) : ref(true);
watch(
theme,
(newVal, oldVal) => {
console.log(newVal);
if (newVal) {
window.document.documentElement.setAttribute("data-theme", "light");
} else {
window.document.documentElement.setAttribute("data-theme", "dark");
}
},
{
immediate: true,
}
);
</script>
index.vue
<template>
<div>
<darkLight />
<!-- 测试用 -->
<el-card class="box-card">
<template #header>
<div class="card-header">
<span>Card name</span>
</div>
</template>
</el-card>
</div>
</template>
<script setup lang='ts'>
import darkLight from '@/components/darkLight.vue'
</script>
base.css
或者全局搜索 :root 在后面加修饰,white代表亮色,dark代表暗黑色,加对应的修饰即可
/* semantic color variables for this project */
:root[data-theme=ligth] {
--color-background: var(--vt-c-white);
}
@media (prefers-color-scheme: dark) {
:root[data-theme=dark] {
--color-background: var(--vt-c-black);
}
}