'How to toggle to dark mode in Vue JS and Tailwind CSS
I want to toggle to dark mode in Vue JS and Tailwind CSS with Dark class in tailwind, but I don't have idea what I should do. I code a little and I want to try something with v-if, like v-if ="isDark === true"
the class(Tailwind) active dark mode like <div class="flex justify-center mt-4 bg-white dark:bg-black">
.
Obs: I active dark mode in tailwind.config.js with darkMode: 'class'
Here's what I code:
<button href="" class="px-2 mb-1" @click="isDark = !isDark">
<img src="../Assets/Icons/moon.svg" alt="" class="w-6 h-5 hidden lg:flex md:flex" v-if="isDark === true">
<img src="../Assets/Icons/sun.svg" alt="" class="w-6 h-5 hidden lg:flex md:flex" v-if="isDark === false">
</button>
<script>
export default {
setup(){
const showSidebar = ref(false)
const stayInDropdown = ref(true)
const isDark = ref(true)
return{
showSidebar,
stayInDropdown,
isDark,
}
},
</script>
Solution 1:[1]
I just added :class="isDark ? 'dark' : ''"
in my div who contains all my code and work's!
Solution 2:[2]
Try to watch the isDark
property and add/remove the dark
class from the body element :
<script>
export default {
setup(){
const showSidebar = ref(false)
const stayInDropdown = ref(true)
const isDark = ref(true)
watch(isDark,(val)=>{
val?document.body.classList.add("dark"): document.body.classList.remove("dark")
})
return{
showSidebar,
stayInDropdown,
isDark,
}
},
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | GuilhermeBS |
Solution 2 |