如何在 Vue JS 和 Tailwind 中切换到暗模式 CSS

How to toggle to dark mode in Vue JS and Tailwind CSS

我想在 Vue JS 和 Tailwind CSS 中切换到黑暗模式,在 Tailwind 中切换到黑暗模式 class,但我不知道该怎么做。我编写了一些代码,我想用 v-if 尝试一些东西,比如 v-if ="isDark === true" class(Tailwind) 主动暗模式,比如 <div class="flex justify-center mt-4 bg-white dark:bg-black">
Obs:我在 tailwind.config.js 中使用暗模式激活暗模式:'class'
这是我的代码:

<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>

尝试从正文元素中查看 isDark 属性 和 add/remove dark class :

<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>

我刚刚在我的 div 中添加了 :class="isDark ? 'dark' : ''",其中包含我所有的代码和工作!