Last active
September 25, 2019 20:09
-
-
Save ericdfields/3b1db5d03a0396ee7f08061b918162ac to your computer and use it in GitHub Desktop.
Globally available dark mode support in a Nuxt (Vue.js) app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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") | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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