为什么弃用 Vue 的 Transition
vue 的 transition 在 v-if v-show,display none 的时候会导致动画不触发,得加 setTimeout
<template>
<div>
<Transition
@before-enter="onBeforeEnter"
@enter="onEnter"
@after-enter="onAfterEnter"
@enter-cancelled="onEnterCancelled"
@before-leave="onBeforeLeave"
@leave="onLeave"
@after-leave="onAfterLeave"
@leave-cancelled="onLeaveCancelled"
>
<!-- ... -->
</Transition>
</div>
</template>
<script>
export default {
methods: {
onBeforeEnter(el) {
setTimeout(() => {
el.style.transform = "translateX(0)";
}, 10);
},
onEnter(el, done) {
// 动画事件
console.log("onEnter", el);
// 这时候发现 display 还是 none
done();
},
onAfterEnter(el) {
// ...
},
onEnterCancelled(el) {
// ...
},
onBeforeLeave(el) {
// ...
},
onLeave(el, done) {
// ...
done();
},
onAfterLeave(el) {
// ...
},
onLeaveCancelled(el) {
// ...
},
},
};
</script>
复现的 js 代码
function modifyElementStyle(element, initialStyles, finalStyles, delay) {
if (!(element instanceof HTMLElement)) {
console.error("Invalid element provided.");
return;
}
// 设置初始样式
Object.assign(element.style, initialStyles);
// 延迟后设置最终样式以触发动画
setTimeout(function () {
Object.assign(element.style, finalStyles);
}, delay);
}
let style = {
width: 500 + "px",
"margin-right": `-${500}px`,
transition: "all 1s ease",
display: "none",
};
let nextStyle = {
width: 500 + "px",
transition: "all 1s ease",
"margin-right": `-${0}px`,
display: "block",
};
modifyElementStyle(
el,
style,
nextStyle,
1000 // 延迟 1 秒
);