37 lines
1.1 KiB
JavaScript
37 lines
1.1 KiB
JavaScript
import { computed, ref } from 'vue'
|
|
|
|
const isDarkMode = ref(false)
|
|
let initialized = false
|
|
|
|
const applyTheme = (dark) => {
|
|
isDarkMode.value = Boolean(dark)
|
|
document.documentElement.classList.toggle('dark-mode', isDarkMode.value)
|
|
document.body.classList.toggle('dark-mode', isDarkMode.value)
|
|
document.documentElement.style.colorScheme = isDarkMode.value ? 'dark' : 'light'
|
|
}
|
|
|
|
export const initializeTheme = () => {
|
|
if (initialized || typeof window === 'undefined') return
|
|
|
|
const savedTheme = localStorage.getItem('darkMode')
|
|
const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches
|
|
applyTheme(savedTheme === null ? prefersDark : savedTheme === 'true')
|
|
initialized = true
|
|
}
|
|
|
|
export const useTheme = () => {
|
|
initializeTheme()
|
|
|
|
const toggleTheme = () => {
|
|
applyTheme(!isDarkMode.value)
|
|
localStorage.setItem('darkMode', String(isDarkMode.value))
|
|
}
|
|
|
|
return {
|
|
isDarkMode,
|
|
themeIcon: computed(() => (isDarkMode.value ? 'fas fa-sun' : 'fas fa-moon')),
|
|
themeLabel: computed(() => (isDarkMode.value ? '切换到浅色模式' : '切换到深色模式')),
|
|
toggleTheme,
|
|
}
|
|
}
|