下文代码基于
- vue 3.x
import { ref, onMounted } from 'vue';
import type { Ref } from 'vue';
/**
* 深色模式
*/
const mqList = window.matchMedia?.('(prefers-color-scheme: dark)');
const theme: Ref<'light' | 'dark'> = ref(mqList.matches ? 'dark' : 'light');
onMounted(() => {
mqList.addEventListener('change', (event) => {
if (event.matches) {
theme.value = 'dark';
} else {
theme.value = 'light';
}
});
});