Skip to content

Instantly share code, notes, and snippets.

@13protons
Last active March 11, 2021 20:43
Show Gist options
  • Save 13protons/4994caf60387804032b99da56b62f427 to your computer and use it in GitHub Desktop.
Save 13protons/4994caf60387804032b99da56b62f427 to your computer and use it in GitHub Desktop.
Vue 2.x plugin to detect dark mode and make a reactive property describing the current mode available to all components of your app
export default function Plugin(Vue) {
/**
Installing in your app root:
import DarkMode from './path/to/this/code.js';
Vue.use(DarkMode);
Usage in your components:
<div v-if="$darkMode.isDark">...</div>
-or-
if(this.$darkMode.isDark) {
...
}
*/
// an object to encapsulate observate state and the update method
const darkMode = {
// make it reactive!
state: Vue.observable({
// default mode is light
isDark: false,
isLight: true
}),
update(event) {
// mutate the observable props
if (event.matches) {
darkMode.state.isDark = true;
darkMode.state.isLight = false;
} else {
darkMode.state.isDark = false;
darkMode.state.isLight = true;
}
}
}
// only bother checking for dark mode if the browser supports it.
if (window.matchMedia) {
// the media query to match
const darkQuery = '(prefers-color-scheme: dark)';
darkMode.update(window.matchMedia(darkQuery));
window.matchMedia(darkQuery)
.addEventListener('change', darkMode.update);
}
// expose just the observable props the app's components
Vue.prototype.$darkMode = darkMode.state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment