File tree Expand file tree Collapse file tree 4 files changed +45
-0
lines changed Expand file tree Collapse file tree 4 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 2
2
import { storeToRefs } from ' pinia'
3
3
import useAppStore from ' @/stores/modules/app'
4
4
import useRouteTransitionNameStore from ' @/stores/modules/routeTransitionName'
5
+ import useAutoThemeSwitcher from ' @/hooks/useAutoThemeSwitcher'
5
6
6
7
useHead ({
7
8
title: ' Vue3 Vant Mobile' ,
@@ -22,6 +23,12 @@ const { mode } = storeToRefs(appStore)
22
23
23
24
const routeTransitionNameStore = useRouteTransitionNameStore ()
24
25
const { routeTransitionName } = storeToRefs (routeTransitionNameStore )
26
+
27
+ const { initializeThemeSwitcher } = useAutoThemeSwitcher (appStore )
28
+
29
+ onMounted (() => {
30
+ initializeThemeSwitcher ()
31
+ })
25
32
</script >
26
33
27
34
<template >
Original file line number Diff line number Diff line change
1
+ import type { AppStore } from '@/stores/modules/app'
2
+
3
+ export default function useAutoThemeSwitcher ( appStore : AppStore ) {
4
+ const handleAttributeChange = ( ) => {
5
+ const rootElement = document . documentElement
6
+ if ( rootElement . classList . contains ( 'dark' ) )
7
+ appStore . swithMode ( 'dark' )
8
+ else
9
+ appStore . swithMode ( 'light' )
10
+ }
11
+
12
+ const observerOptions = {
13
+ attributes : true ,
14
+ attributeFilter : [ 'class' ] ,
15
+ }
16
+
17
+ const observer = new MutationObserver ( handleAttributeChange )
18
+
19
+ const targetElement = document . querySelector ( 'html' )
20
+
21
+ const initializeThemeSwitcher = ( ) => {
22
+ observer . observe ( targetElement , observerOptions )
23
+ }
24
+
25
+ return { initializeThemeSwitcher }
26
+ }
Original file line number Diff line number Diff line change 1
1
import { defineStore } from 'pinia'
2
2
import type { ConfigProviderTheme } from 'vant'
3
3
4
+ export interface AppStore {
5
+ swithMode : ( val : ConfigProviderTheme ) => void
6
+ }
7
+
4
8
const prefersDark
5
9
= window . matchMedia
6
10
&& window . matchMedia ( '(prefers-color-scheme: dark)' ) . matches
Original file line number Diff line number Diff line change @@ -11,6 +11,14 @@ definePage({
11
11
const appStore = useAppStore ()
12
12
const checked = ref <boolean >(isDark .value )
13
13
14
+ watch (
15
+ () => isDark .value ,
16
+ (newMode ) => {
17
+ checked .value = newMode
18
+ },
19
+ { immediate: true },
20
+ )
21
+
14
22
function toggle() {
15
23
toggleDark ()
16
24
appStore .swithMode (isDark .value ? ' dark' : ' light' )
You can’t perform that action at this time.
0 commit comments