如何在Vue3中实现深色/浅色模式?

huangapple go评论134阅读模式
英文:

How to implement dark/light mode in vue3?

问题

我想知道如何在我的Vue 3项目中添加暗模式/亮模式。我知道来自'@vueuse/core'的**useDarkuseToggle**,但我不确定如何在我的应用程序的每个组件中实现它们。

const isDark = useDark({
  selector: 'body',
  attribute: 'color-scheme',
  valueDark: 'dark',
  valueLight: 'light',
})

我应该为页面上的每个HTML元素创建多个对象吗?这似乎比以前的选项更耗时。而且我如何在我的子组件中使用**isDark**?

目前,我正在使用Pinia store来存储关于模式是暗模式还是亮模式的信息。然后,我在每个组件的每个HTML元素中使用这个值来应用'dark'或'light'类。然而,这种方法很耗时,我相信一定有更好的处理方法。

英文:

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.

答案1

得分: 1

不需要在每个子组件中实现暗/亮模式。相反,您只需要将其添加到应用程序/根组件中。类似于:

<template>
  <div :class="{ dark: isDark }">
    ...
  </div>
</template>
...
<script setup>
const darkModeStore = useDarkModeStore();
const isDark = computed(() => darkModeStore.mode === 'dark');
</script>

并且在您的通用样式中:

<style>
/* 暗模式样式 */
.dark h1 {
  color: #fff;
}
</style>

或者在特定子组件中:

<style scoped>
.dark .child-component h1 {
  color: red;
}
</style>
英文:

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

&lt;template&gt;
  &lt;div :class=&quot;{ dark: isDark }&quot;&gt;
    ...
  &lt;/div&gt;
&lt;/template&gt;
...
&lt;script setup&gt;
const darkModeStore = useDarkModeStore();
const isDark = computed(() =&gt; darkModeStore.mode === &#39;dark&#39;);
&lt;/script&gt;

And in your style general

&lt;style&gt;
/* Styles for dark mode */
.dark h1 {
  color: #fff;
}
&lt;/style&gt;

Or in child specific

&lt;style scoped&gt;
.dark .child-component h1 {
  color: red;
}
&lt;/style&gt;

huangapple
  • 本文由 发表于 2023年6月29日 16:56:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定