最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to toggle :root --color-scheme lightdark from pinia with vuetify? - Stack Overflow

programmeradmin2浏览0评论

I recently added custom light/dark color schemes to a Vuetify app and the user can toggle between them and that works well, except for one thing: the scroll bar color doesn't change. In browser dev tools I traced it down to this bit of CSS:

:root {
    color-scheme: dark;
}

If I switch to the light theme, that CSS is still there, still set to dark, and the scroll bar remains dark. If I uncheck it in dev tools, it turns light.

I couldn't find anything in Vuetify that addressed this, so I figured I'd do it myself. I change the theme with a pinia store, and I figured on the switch to light I'd grab the root and adjust it. But from my pinia store function, document.documentElement is null:

import { computed } from "vue"
import { defineStore } from "pinia"
import { usePreferredDark, useStorage } from "@vueuse/core"

const isDark = usePreferredDark()

export const useAppearanceStore = defineStore("appearance", () => {
  const dark = useStorage("tiara-dark", isDark ? true : false)
  const lightOrDarkString = computed(() => {
    return dark.value ? "dark" : "light"
  })
  const theme = computed(() => {
    return dark.value ? "tiaraDark1" : "tiaraLight1"
  })
  function toggleDark() {
    dark.value = !dark.value
    console.log(document.documentElement) // prints null
    if (!dark.value) {
      document.documentElement.style.setProperty('--color-scheme', 'light')
    }
  }

  return { theme, dark, lightOrDarkString, toggleDark }
})

So then I tried passing in the root element as an argument. In the component with the toggle switch:

onMounted(() => {
  root = document.documentElement
})
@click="appearance.toggleDark(root)"

And in pinia store:

function toggleDark(root) {
    dark.value = !dark.value
    console.log(root) // now it's there
    if (!dark.value) {
      root.style.setProperty('--color-scheme', 'light')
    }
  }

But it still doesn't work. Now the <html> element gets --color-scheme: light, but the :root is still there with --color-scheme: dark, and the scroll bar is still dark.

Why is :root's color-scheme still set to dark after I change the theme to a light theme in Vuetify? And how can I fix it?

Versions:

    "@vueuse/core": "^12.8.2",
    "pinia": "^3.0.1",
    "vue": "^3.5.13",
    "vue-router": "^4.5.0",
    "vuetify": "^3.7.15"
发布评论

评论列表(0)

  1. 暂无评论