英文:
How to implement dark/light mode in vue3?
问题
我想知道如何在我的Vue 3项目中添加暗模式/亮模式。我知道来自'@vueuse/core'的**useDark
和useToggle
**,但我不确定如何在我的应用程序的每个组件中实现它们。
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
<template>
<div :class="{ dark: isDark }">
...
</div>
</template>
...
<script setup>
const darkModeStore = useDarkModeStore();
const isDark = computed(() => darkModeStore.mode === 'dark');
</script>
And in your style general
<style>
/* Styles for dark mode */
.dark h1 {
color: #fff;
}
</style>
Or in child specific
<style scoped>
.dark .child-component h1 {
color: red;
}
</style>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论