如何让组件无需等待子元素过渡动画完成?
解决Svelte表单隐藏时等待子元素过渡的问题
方法1:用invalidate强制中断子元素过渡
给带滑动过渡的子元素添加invalidate配置,绑定父元素的显示状态。当父元素要隐藏时,子元素的过渡会立即终止,父元素无需等待过渡完成:
<script> import { slide } from 'svelte/transition'; let showForm = true; let showSubControl = true; </script> <button on:click={() => showForm = !showForm}>切换表单</button> {#if showForm} <form> {#if showSubControl} <div transition:slide={{ invalidate: showForm }}> 带滑动过渡的子控件 </div> {/if} <!-- 其他表单控件 --> </form> {/if}
方法2:用{#key}块强制组件销毁重建
通过{#key}绑定切换标识,切换表单时旧表单会被直接销毁,跳过子元素过渡等待流程:
<script> import { slide } from 'svelte/transition'; let activeForm = 'form1'; let showSubControl = true; </script> <button on:click={() => activeForm = activeForm === 'form1' ? 'form2' : 'form1'}>切换表单</button> {#key activeForm} {#if activeForm === 'form1'} <form> {#if showSubControl} <div transition:slide> 带滑动过渡的子控件 </div> {/if} <!-- 表单1内容 --> </form> {:else} <form> <!-- 表单2内容 --> </form> {/if} {/key}
方法3:手动控制过渡状态
在切换表单前,先关闭子控件的显示,再立即隐藏父表单:
<script> import { slide } from 'svelte/transition'; let showForm = true; let showSubControl = true; async function toggleForm() { showSubControl = false; await Promise.resolve(); // 触发DOM更新 showForm = false; } </script> <button on:click={toggleForm}>切换表单</button> {#if showForm} <form> {#if showSubControl} <div transition:slide> 带滑动过渡的子控件 </div> {/if} <!-- 其他表单控件 --> </form> {/if}
内容的提问来源于stack exchange,提问作者Nikolay Dyankov
相关产品推荐
相关产品推荐

