fix: rework setup to improve SSR compatibility
This commit is contained in:
parent
fd7d30a38a
commit
d8d163dbd0
22 changed files with 137 additions and 73 deletions
41
plugins/setup-color-mode.ts
Normal file
41
plugins/setup-color-mode.ts
Normal file
|
@ -0,0 +1,41 @@
|
|||
import type { ColorMode } from '~/types'
|
||||
import { InjectionKeyColorMode } from '~/constants/symbols'
|
||||
import { COOKIE_KEY_COLOR_MODE } from '~/constants'
|
||||
|
||||
export default defineNuxtPlugin((nuxt) => {
|
||||
const cookieColorMode = useCookie<ColorMode | null>(COOKIE_KEY_COLOR_MODE, { default: () => null })
|
||||
|
||||
const preferColorMode = process.server ? computed(() => 'light') : usePreferredColorScheme()
|
||||
const colorMode = computed<ColorMode>({
|
||||
get() {
|
||||
return cookieColorMode.value || preferColorMode.value as ColorMode
|
||||
},
|
||||
set(value) {
|
||||
cookieColorMode.value = value
|
||||
},
|
||||
})
|
||||
|
||||
nuxt.vueApp.provide(InjectionKeyColorMode, colorMode)
|
||||
|
||||
if (process.server) {
|
||||
useHead({
|
||||
htmlAttrs: {
|
||||
class: colorMode,
|
||||
},
|
||||
})
|
||||
}
|
||||
else {
|
||||
watchEffect(() => {
|
||||
document.documentElement.classList.toggle('dark', colorMode.value === 'dark')
|
||||
document.documentElement.classList.toggle('light', colorMode.value === 'light')
|
||||
})
|
||||
}
|
||||
|
||||
useHead({
|
||||
meta: [{
|
||||
id: 'theme-color',
|
||||
name: 'theme-color',
|
||||
content: computed(() => colorMode.value === 'dark' ? '#111111' : '#ffffff'),
|
||||
}],
|
||||
})
|
||||
})
|
Loading…
Add table
Add a link
Reference in a new issue