Created
March 31, 2020 19:42
-
-
Save BhargzShukla/44cc1fd69889840b86f8e4c11f469a3c to your computer and use it in GitHub Desktop.
Vue code to toggle theme based on data-* attributes
This file contains 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
<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