Theme Switching for Light/Dark Mode
Toggle between light and dark themes based on mobile system preferences using Vue 3 reactive references, enhancing user customization on mobile apps.
import { ref } from 'vue';
export default {
setup() {
// Reactive reference for theme (null at the beginning to use system preference)
const theme = ref(null);
// Computed property to determine the theme class
const themeClass = computed(() => theme.value ? `theme-${theme.value}` : '');
// Watch for changes in the system preference using the matchMedia API
const preferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
theme.value = preferredTheme;
// Listen to changes in the system preference
window.matchMedia('(prefers-color-scheme: dark)').addListener(e => {
theme.value = e.matches ? 'dark' : 'light';
});
// Method to toggle the theme
function toggleTheme() {
theme.value = theme.value === 'light' ? 'dark' : 'light';
}
return { theme, themeClass, toggleTheme };
},
};
This code sets up a Vue 3 component that reacts to the system's preferred color scheme and provides a method to toggle between light and dark themes. It uses a `ref` to keep track of the theme, a `computed` property to apply a corresponding class, and a watcher via `matchMedia` to detect changes in the OS-level preference.