0👍
After digging and creating an issue in the vueuse repo the solution was found below with an explanation.
0👍
What you need is a watch to watch the state of prefrence of user. It’s a good idea to implement a watch to track the user’s preference. By doing this, you can control the timing and order of operations when the preference changes, which will help address the issue with the transition not occurring smoothly.
Here’s an example of how you might update your script:
<script setup>
import { useDark, useToggle } from '@vueuse/core';
import { watch } from 'vue';
const isDark = useDark();
const toggleDark = useToggle(isDark);
// watch the isDark ref to manage transitions
watch(isDark, (newVal) => {
// toggle the 'dark' class on the documentElement after a delay
setTimeout(() => {
document.documentElement.classList.toggle('dark', newVal);
}, 150);
});
</script>
<template>
<button
class="h-8 w-16 pl-1 rounded-full bg-slate-300"
type="button"
@click="toggleDark()"
>
<div
class="h-7 w-7 rounded-full bg-slate-400 transition-all"
:class="{ 'translate-x-7': isDark }"
/>
</button>
</template>
When isDark changes (i.e., when the user toggles the button), it triggers a function that waits for a short delay before toggling the ‘dark’ class on the document. This delay ensures that the transition classes have been applied before the ‘dark’ class is toggled, creating a smooth transition effect.
Hope this helps! 🌷