SoFunction
Updated on 2025-04-05

UseDark to parse, and found that the transition animation is invalid

Let's take an example first

<template>
  <div class="theme-change">
      <button
        class="switch"
        @click="toggleTheme"
        role="switch"
        aria-label="Switch dark theme"
        :class="{
          k: isDark
        }"
      >
        Button
      </button>
  </div>
</template>
<script setup lang="ts">
const isDark = useDark();
function toggleTheme() {
   =  ? false : true;
}
</script>
<style scoped lang="scss">
.theme-change {
  .switch {
    transition: all 3s;
    background: green;
  }
}
. {
  background: red;
}
</style>

The above code will not have a transition effect of background color when clicking the button.

If you change the code

// const isDark = useDark();
const isDark = ref(false);

Transition effect

Only then will there be a transition effect.

useDark() lets the html element add dark class name. If you do not useDark(), use the following method

// const isDark = useDark();
const isDark = ref(false);
function toggleTheme() {
  ('dark')
   =  ? false : true;
}

It also has a transitional effect.

Is there anyone who knows why using useDark() causes the transition effect to fail and the reason cannot be found?

The above is the detailed content of analyzing the useDark() and discovering the failure of transition animation. For more information about the failure of useDark() transition animation, please follow my other related articles!