Skip to content

Instantly share code, notes, and snippets.

@leoramos086
Last active June 11, 2021 21:04
Show Gist options
  • Select an option

  • Save leoramos086/afd64fd0a54b1d7bf0de453ab7be69c6 to your computer and use it in GitHub Desktop.

Select an option

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
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