5. useColorMode (feat. vueuse)
App.vue
<script setup>
import { useColorMode } from "@vueuse/core";
import IconSun from "./components/IconSun";
import IconMoon from "./components/IconMoon";
import IconCafe from "./components/IconCafe";
const colorMode = useColorMode({
modes: {
cafe: "cafe",
},
});
const switchToCafe = () => {
colorMode.value = "cafe";
};
const switchTheme = () => {
if (colorMode.value === "dark") {
colorMode.value = "cafe";
} else if (colorMode.value === "cafe") {
colorMode.value = "light";
} else {
colorMode.value = "dark";
}
};
</script>
<template>
<header>
<h1>{{ colorMode }}</h1>
<button type="button" @click="switchTheme">
<IconSun v-if="colorMode === 'light'" />
<IconMoon v-else-if="colorMode === 'dark'" />
<IconCafe v-else />
</button>
<button type="button" @click="switchToCafe">Switch to Cafe</button>
</header>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.cafe {
filter: sepia(0.9) hue-rotate(315deg) brightness(0.9);
}
.dark {
background-color: #222;
color: #fff;
}
</style>
components/IconCafe.vue
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 24 24"
>
<path
fill="currentColor"
d="M20 3H6c-1.1 0-2 .9-2 2v8c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 5h-2V5h2v3zM3 21h16c.55 0 1-.45 1-1s-.45-1-1-1H3c-.55 0-1 .45-1 1s.45 1 1 1z"
/>
</svg>
</template>
components/IconMoon.vue
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 24 24"
>
<path
fill="currentColor"
d="M12.01 12c0-3.57 2.2-6.62 5.31-7.87c.89-.36.75-1.69-.19-1.9c-1.1-.24-2.27-.3-3.48-.14c-4.51.6-8.12 4.31-8.59 8.83C4.44 16.93 9.13 22 15.01 22c.73 0 1.43-.08 2.12-.23c.95-.21 1.1-1.53.2-1.9A8.46 8.46 0 0 1 12.01 12z"
/>
</svg>
</template>
components/IconSun.vue
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 24 24"
>
<path
fill="currentColor"
d="m6.76 4.84l-1.8-1.79l-1.41 1.41l1.79 1.79l1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41l-1.79 1.79l1.41 1.41l1.79-1.79zm-3.21 13.7l1.79 1.8l1.41-1.41l-1.8-1.79l-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6s6-2.69 6-6s-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41l1.79-1.8l-1.41-1.41l-1.79 1.8z"
/>
</svg>
</template>