I'm wondering how to add dark/light mode to my Vue 3 project. I'm aware of useDark
and useToggle
from '@vueuse/core', but I'm unsure how to implement them in every component of my application.
const isDark = useDark({
selector: 'body',
attribute: 'color-scheme',
valueDark: 'dark',
valueLight: 'light',
})
Should I create multiple objects for every HTML element on my page? It seems even more time-consuming than the previous option. And how can I use isDark
in my child components?
Currently, I'm using a Pinia store to store information about whether the mode is set to dark or light. I then use this value in every HTML element of every component to apply the 'dark' or 'light' class. However, this approach is time-consuming, and I believe there must be a better way to handle this.
You don't need to implement dark/light mode in every child component. Instead you just need to add it to the app/root component. Something like
<template>
<div :class="{ dark: isDark }">
...
</div>
</template>
...
<script setup>
const darkModeStore = useDarkModeStore();
const isDark = computed(() => darkModeStore.mode === 'dark');
</script>
And in your style general
<style>
/* Styles for dark mode */
.dark h1 {
color: #fff;
}
</style>
Or in child specific
<style scoped>
.dark .child-component h1 {
color: red;
}
</style>