you need to save dark mode in cookies and use nuxt store to set, get and togggle dark mode, also in template you need to set conditional chakra componet according to value of darkmode in nuxt store
modules needed:
- cookie-universal-nuxt
nuxt with chakra ui persisting the color mode - fix flashing issue too |
<!-- layouts/default.vue --> | |
<template> | |
<CThemeProvider> | |
<CColorModeProvider> | |
<component :is="isDark ? 'CDarkMode': 'CLightMode'"> | |
<CBox font-family="body" as="main"> | |
<CReset /> | |
<div class="container"> | |
<CBox v-bind="mainStyles[colorMode]" d="flex" w="100vw" h="100vh" flex-dir="column" | |
justify-content="center"> | |
<NavBar /> | |
<Nuxt keep-alive /> | |
</CBox> | |
</div> | |
</CBox> | |
</component> | |
</CColorModeProvider> | |
</CThemeProvider> | |
</template> | |
<script> | |
import { | |
CDarkMode, | |
CLightMode | |
} from '@chakra-ui/vue' | |
import NavBar from '~/components/NavBar.vue'; | |
export default { | |
name: 'DefaultLayout', | |
components: { | |
CDarkMode, | |
CLightMode, | |
NavBar | |
}, | |
data () { | |
return { | |
showModal: false, | |
mainStyles: { | |
dark: { | |
bg: 'gray.700', | |
color: 'whiteAlpha.900' | |
}, | |
light: { | |
bg: 'white', | |
color: 'gray.900' | |
} | |
} | |
} | |
}, | |
computed: { | |
isDark() { | |
return this.$store.getters.getDarkMode | |
}, | |
colorMode () { | |
return this.isDark ? 'dark' : 'light' | |
} | |
} | |
} | |
</script> |
// store/index.js | |
export const state = () => ({ | |
isDark: false | |
}) | |
export const getters = { | |
getDarkMode(state) { | |
return state.isDark | |
} | |
} | |
export const mutations = { | |
toggleDarkMode(state) { | |
state.isDark = !state.isDark | |
}, | |
setDarkMode(state, mode) { | |
state.isDark = mode | |
}, | |
} | |
export const actions = { | |
nuxtServerInit({ commit }, { app }) { | |
commit('setDarkMode', app.$cookies.get('isDark') || false) | |
} | |
} |