Skip to content
On this page

useTheme

Vue composable to handling UI theme - Automatically set dark and light theme and switch between them

Usage





Data


{ "hasDarkTheme": false, "hasLightTheme": false }

How to use it ?

INFO

autoSetTheme method, does not store theme value in localStorage to always let user preferences apply on every visit (some users automatically have light mode during the day and dark at night)

TIP

Always run autoSetTheme method on app initialization and let user change the theme with toggleTheme or setDarkTheme or setLightTheme

Example

App.vue or layouts/default.vue

vue
<template>
  <div
    class="app"
    :class="{
      '--has-dark-theme': hasDarkTheme,
      '--has-light-theme': hasLightTheme,
    }"
  >
    <!-- Theme switching -->
    <ZvButton @click="toggleTheme"> Click to toggle mode </ZvButton>

    <ZvButton @click="setDarkTheme"> Click to set dark mode </ZvButton>

    <ZvButton @click="setLightTheme"> Click to set light mode </ZvButton>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted } from 'vue'

  import ZvButton from '@zadigetvoltaire/ui/components/ZvButton'

  import { useTheme, type ThemeOptions } from '@zadigetvoltaire/ui'

  // optional
  const options: ThemeOptions = {
    /* should be "dark" to works with @zadigetvoltaire/ui */
    darkClass: 'dark',
    /* local storage preferences */
    storageThemeKey: 'theme',
    storageThemeValueDark: 'dark',
    storageThemeValueLight: 'light',
  }

  const { autoSetTheme, toggleTheme, setDarkTheme, setLightTheme, theme, hasDarkTheme, hasLightTheme } =
    useTheme(options)

  onMounted(() => {
    /*
     * Will automatically set the theme according
     * with the user preferences and add class to <html /> element
     */
    autoSetTheme()
  })
</script>