Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ericdfields
Last active September 25, 2019 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericdfields/3b1db5d03a0396ee7f08061b918162ac to your computer and use it in GitHub Desktop.
Save ericdfields/3b1db5d03a0396ee7f08061b918162ac to your computer and use it in GitHub Desktop.
Globally available dark mode support in a Nuxt (Vue.js) app
/* store/const.js */
export const state = () => ({
darkMode: false
});
export const mutations = {
setDarkMode: state => {
state.darkMode = true;
},
unsetDarkMode: state => {
state.darkMode = false;
}
};
export const actions = {
setDarkMode: ({ commit }) => commit("setDarkMode"),
unsetDarkMode: ({ commit, state }) => state.darkMode && commit("unsetDarkMode")
};
/* layouts/default.vue */
<template>
<nuxt />
</template>
<script>
export default {
components: {
AdminNav
},
data() {
return {
mql: window.matchMedia('(prefers-color-scheme: dark)')
}
},
created() {
this.darkMode(this.mql)
this.mql.addListener(this.darkMode)
},
beforeDestroy() {
this.mql.removeListener(this.darkMode)
},
methods: {
darkMode: function(e) {
if (e.matches) {
return this.$store.dispatch('const/setDarkMode')
}
return this.$store.dispatch('const/unsetDarkMode')
}
}
}
</script>
/* components/myComponent.vue */
<template>
<sui-button primary inverted="darkMode" icon="plus">New entity</sui-button>
</template>
<script>
export default {
computed: {
darkMode() {
return this.$store.state.const.darkMode
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment