Merge pull request #68 from jjjokin/feat-auto-switch-theme

This commit is contained in:
jxxghp
2024-01-08 11:01:26 +08:00
committed by GitHub
3 changed files with 29 additions and 15 deletions
+17 -13
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from 'vue' import { ref } from 'vue'
import { useTheme } from 'vuetify' import { useTheme } from 'vuetify'
import type { ThemeSwitcherTheme } from '@layouts/types' import type { ThemeSwitcherTheme } from '@layouts/types'
@@ -20,26 +20,30 @@ const {
{ initialValue: savedTheme.value }, { initialValue: savedTheme.value },
) )
function changeTheme() { function updateTheme() {
const nextTheme = getNextThemeName() const autoTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
const theme = currentThemeName.value === 'auto' ? autoTheme : currentThemeName.value
globalTheme.name.value = nextTheme globalTheme.name.value = theme
savedTheme.value = nextTheme savedTheme.value = theme
localStorage.setItem('theme', nextTheme)
// 修改载入时背景色 // 修改载入时背景色
localStorage.setItem('materio-initial-loader-bg', globalTheme.current.value.colors.background) localStorage.setItem('materio-initial-loader-bg', globalTheme.current.value.colors.background)
themeTransition() themeTransition()
} }
// Update icon if theme is changed from other sources // 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateTheme)
watch( watch(
() => globalTheme.name.value, () => currentThemeName.value,
(val) => { () => updateTheme(),
currentThemeName.value = val
},
) )
function changeTheme() {
const nextTheme = getNextThemeName()
currentThemeName.value = nextTheme
localStorage.setItem('theme', nextTheme)
}
// Apply saved theme on page load // Apply saved theme on page load
// onMounted(() => { // onMounted(() => {
// globalTheme.name.value = savedTheme.value // globalTheme.name.value = savedTheme.value
+8 -2
View File
@@ -3,9 +3,15 @@ import { useToast } from 'vue-toast-notification'
import { useTheme } from 'vuetify' import { useTheme } from 'vuetify'
import store from './store' import store from './store'
function setTheme() {
const { global: globalTheme } = useTheme()
let theme = localStorage.getItem('theme') || 'light'
if (theme === 'auto')
theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
globalTheme.name.value = theme
}
// 第一时间应用主题 // 第一时间应用主题
const { global: globalTheme } = useTheme() setTheme()
globalTheme.name.value = localStorage.getItem('theme') || 'light'
// 提示框 // 提示框
const $toast = useToast() const $toast = useToast()
@@ -14,6 +14,10 @@ const themes: ThemeSwitcherTheme[] = [
name: 'purple', name: 'purple',
icon: 'mdi-brightness-4', icon: 'mdi-brightness-4',
}, },
{
name: 'auto',
icon: 'mdi-brightness-auto',
},
] ]
</script> </script>