Last active
June 11, 2021 21:04
-
-
Save leoramos086/afd64fd0a54b1d7bf0de453ab7be69c6 to your computer and use it in GitHub Desktop.
Vue Hook Color Scheme - Hook verifica se o ambiente esta em dark mode e adiciona um atributo 'theme-dark' no elemento html (<html theme-dark>) podendo alterna os estilos
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
| import { reactive, readonly } from 'vue' | |
| export interface IColorScheme { | |
| colorScheme: 'dark' | 'light' | |
| isDarkMode: boolean | |
| } | |
| const state = reactive<IColorScheme>({ | |
| colorScheme: 'light', | |
| isDarkMode: false | |
| }) | |
| export default function useColorScheme (): IColorScheme { | |
| return readonly(state) | |
| } | |
| export function startColorScheme (): void { | |
| const preferesColorScheme = window.matchMedia('(prefers-color-scheme: dark)') | |
| if (preferesColorScheme.matches) { | |
| state.colorScheme = 'dark' | |
| state.isDarkMode = true | |
| activeDarkMode() | |
| } | |
| } | |
| export function toggleColorScheme (): void { | |
| state.isDarkMode = !state.isDarkMode | |
| if (state.isDarkMode) { | |
| activeDarkMode() | |
| } else { | |
| disableDarkMode() | |
| } | |
| } | |
| function activeDarkMode (): void { | |
| document.getElementsByTagName('html')[0].setAttribute('theme-dark', '') | |
| } | |
| function disableDarkMode (): void { | |
| document.getElementsByTagName('html')[0].removeAttribute('theme-dark') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment