Skip to content

Instantly share code, notes, and snippets.

@BhargzShukla
Created March 31, 2020 19:42
Show Gist options
  • Save BhargzShukla/44cc1fd69889840b86f8e4c11f469a3c to your computer and use it in GitHub Desktop.
Save BhargzShukla/44cc1fd69889840b86f8e4c11f469a3c to your computer and use it in GitHub Desktop.
Vue code to toggle theme based on data-* attributes
<template>
<button @click="toggleTheme"><!-- Sun/Moon Icon --></button>
</template>
<script>
export default {
data() {
return {
theme: 'light' // default theme to use when the site is first loaded
}
},
watch: {
theme(theme) {
document.documentElement.dataset.theme = theme // this is where the magic happens
} // the `dataset.theme` is the data-theme attribute I set in my SCSS file (highlighted above)
},
methods: {
toggleTheme() {
this.theme = this.theme === 'light' ? 'dark' : 'light' // switch themes based on current value of `this.theme`
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment