Performance: JavaScript hooks for transitions
This affects the smoothness and timing of animations during component state changes, impacting interaction responsiveness and visual stability.
const hooks = { beforeEnter(el) { el.style.opacity = '0'; }, enter(el, done) { requestAnimationFrame(() => { el.style.transition = 'opacity 0.5s'; el.style.opacity = '1'; setTimeout(done, 500); }); } };
const hooks = { beforeEnter(el) { // heavy synchronous logic for(let i = 0; i < 100000000; i++) {} el.style.opacity = '0'; }, enter(el, done) { el.style.transition = 'opacity 0.5s'; el.style.opacity = '1'; setTimeout(done, 500); } };
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous logic in hooks | Multiple style changes | Multiple reflows triggered | High paint cost due to layout thrashing | [X] Bad |
| Lightweight hooks with requestAnimationFrame | Minimal style changes | Single reflow | Low paint cost with smooth animation | [OK] Good |
beforeEnter phase in a Vue transition component?before-enter, and the shorthand @ for v-on:.<transition @before-enter="myHook"> uses @before-enter, which is correct. Options A, C, and D use camelCase or incorrect casing.<transition @enter="onEnter"> <div v-if="show">Hello</div> </transition>
show is false, so the element is not rendered. After 1 second, show becomes true, triggering the enter transition.onEnter hook logs 'Enter started' and calls done() immediately. This happens after 1 second when the element appears.<transition @leave="onLeave"> <div v-if="visible">Bye</div> </transition>
onLeave hook should call done() only after the animation finishes to keep the element during transition.done() is called immediately, but the opacity change happens after 500ms, so the transition ends too soon.<transition @leave="handleLeave">
<div v-if="show">Content</div>
</transition>
<script setup>
const show = ref(true)
async function apiCall() {
return new Promise(resolve => setTimeout(resolve, 1000))
}
function handleLeave(el, done) {
// What should go here?
}
</script>apiCall(), then after it resolves, set opacity to 0 and call done() to signal transition end.Pass the test and this pattern moves unknown