Dark Mode
Pixelium Design has extracted all color variables as CSS variables. Based on this, we support dark mode, including both automatic switching following the system and manual switching.
- Follow system: Automatically switch to dark mode using the
@media (prefers-color-scheme: dark)media query. - Manual switch: Manually set the class name on the
htmlnode using theuseThemeModehook.
useThemeMode
useThemeMode switches between dark and light themes by setting a class name on the html node, which affects CSS selectors or certain listeners to change the component's theme colors.
A simple example is shown below:
import { useThemeMode } from '@pixelium/web-vue'
// If on-demand import
// import { useThemeMode } from '@pixelium/web-vue/es'
const [mode, toggle, clear, followMedia] = useThemeMode()mode is a Vue ref variable with three possible values: 'dark' (dark mode), 'light' (light mode), and 'unset' (follows system). The default value is determined by the current @media (prefers-color-scheme: dark) media query. It sets the class name on the html node, so you can switch between dark and light modes by changing its value.
toggle is a function to switch between dark and light modes.
clear is used to switch the theme back to following the system.
followMedia applies the current theme mode according to the @media (prefers-color-scheme: dark) media query to mode.
You can try it here:
matchMedia('(prefers-color-scheme: dark)'): false
<template>
Current Theme: {{ mode }}
<br />
matchMedia('(prefers-color-scheme: dark)'): {{ darkMode }}
<br />
<px-space>
<px-button @click="toggle()">Toggle </px-button>
<px-button @click="clear()" theme="info">Clear Theme</px-button>
</px-space>
</template>
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { useThemeMode } from '@pixelium/web-vue'
// If on-demand import
// import { useThemeMode } from '@pixelium/web-vue/es'
const [mode, toggle, clear] = useThemeMode()
const darkMode = ref(false)
if (typeof window !== 'undefined') {
const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
function handleDarkModeChange(e: MediaQueryListEvent | MediaQueryList) {
darkMode.value = e.matches
}
handleDarkModeChange(darkModeQuery)
darkModeQuery.addEventListener('change', handleDarkModeChange)
onBeforeUnmount(() => {
darkModeQuery.removeEventListener('change', handleDarkModeChange)
})
}
</script>