refactor(toggleThemes): move all theme toggle code to toggleThemes.js and all theme related CSS code to themes.css
This commit is contained in:
37
src/utils/toggleThemes.js
Normal file
37
src/utils/toggleThemes.js
Normal file
@@ -0,0 +1,37 @@
|
||||
import { ref, onMounted, watch } from 'vue';
|
||||
|
||||
export function useTheme() {
|
||||
const isDarkMode = ref(false);
|
||||
|
||||
const updateTheme = () => {
|
||||
if (isDarkMode.value) {
|
||||
document.documentElement.classList.add('dark');
|
||||
} else {
|
||||
document.documentElement.classList.remove('dark');
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
const savedTheme = localStorage.getItem('theme');
|
||||
if (savedTheme) {
|
||||
isDarkMode.value = savedTheme === 'dark';
|
||||
} else {
|
||||
isDarkMode.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
}
|
||||
updateTheme();
|
||||
});
|
||||
|
||||
watch(isDarkMode, () => {
|
||||
updateTheme();
|
||||
localStorage.setItem('theme', isDarkMode.value ? 'dark' : 'light');
|
||||
});
|
||||
|
||||
const toggleTheme = () => {
|
||||
isDarkMode.value = !isDarkMode.value;
|
||||
};
|
||||
|
||||
return {
|
||||
isDarkMode,
|
||||
toggleTheme
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user