Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js delay v-if toggle

I want to delay a v-if toggle so that my element is not removed straight away but after 300 ms. I need to element to be removed from the DOM so I need to use a v-if.

Currently I have a somewhat hacky solution to get this done. I wrapped my v-if statement in a transition and set a transition with .3s.

I am using the opacity here but I am not doing anything with it since I do not want to fade the element out but simply delay the v-if toggle.

My element:

<transition name="delay-display-none">
    <div class="i-need-to-be-removed-after-300-ms"></div>
</transition>

My style:

.delay-display-none-leave-active {
    transition: opacity .3s
}
.delay-display-none-leave-to {
    opacity: 1
}

Is there a better option to get this done instead of this hacky solution?

like image 680
Stephan-v Avatar asked Oct 29 '22 00:10

Stephan-v


1 Answers

If you simply want to force a delayed v-if response and you are already using <transition>, you can kind of trick a delay by using a transition-delay of the duration you want to wait, e.g. transition-delay: 300ms, and setting transition-duration: 0 so that you do not actually fade anything.

An alternative way is to actually delay the update of the variable being passed into v-if. Since the variable is dynamically updated (otherwise you cannot toggle v-if), you can use window.setTimeout(...) to update its value instead, so that you can create a delayed effect. This solution requires slightly more care, because you would want to cancel the same timeout whenever a user quickly toggles the element, for example.

like image 114
Terry Avatar answered Nov 15 '22 05:11

Terry