【问题标题】:How to toggle to dark mode in Vue JS and Tailwind CSS如何在 Vue JS 和 Tailwind CSS 中切换到暗模式
【发布时间】:2022-01-12 18:20:47
【问题描述】:

我想在 Vue JS 和 Tailwind CSS 中切换到深色模式,并在 Tailwind 中使用 Dark 类,但我不知道我应该做什么。我写了一点代码,我想用 v-if 尝试一些东西,比如 v-if ="isDark === true" 类(尾风)活动暗模式,比如<div class="flex justify-center mt-4 bg white dark:bg-black">
Obs:我在 tailwind.config.js 中使用 darkMode: '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>

【问题讨论】:

    标签: vue.js vuejs3 tailwind-css vue-composition-api


    【解决方案1】:

    尝试观察 isDark 属性并从 body 元素中添加/删除 dark 类:

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

    【讨论】:

    • 我把这段代码放在哪里了?我尝试使用脚本但页面崩溃const isDark = ref(true) watch(isDark,(val)=&gt;{ val?document.body.classList.add("dark"): document.body.classList.remove("dark") })
    • 请检查我编辑的答案
    • 页面继续崩溃。 obs:我想要 isDark 切换所有页面,但该属性不在所有 div 中。如果你愿意,我们可以继续不和谐
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2020-07-07
      • 2018-04-13
      • 2022-10-25
      • 2021-12-30
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多