You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte动画期间如何即时切换#if分支内容?

解决方法

核心问题是原代码中ContentB和Drawer被包裹在同一个{:else}块中,Svelte会将整个块作为一个单元处理,销毁时需要等待块内所有元素的退出动画完成,导致ContentB延迟消失。

要实现内容即时切换同时保留Drawer的动画,只需将ContentB和Drawer的渲染逻辑拆分,让它们各自独立响应状态变化:

代码实现

<script>
  let conditional = false;
  // 让Drawer的显示状态与conditional反向同步
  $: showDrawer = !conditional;
</script>

<!-- ContentA/ContentB 直接由conditional控制,即时切换 -->
{#if conditional}
  <ContentA/>
{:else}
  <ContentB/>
{/if}

<!-- Drawer单独控制,退出动画独立执行 -->
{#if showDrawer}
  <Drawer transition:fly>
    <Component />
  </Drawer>
{/if}

<!-- 示例切换按钮 -->
<button on:click={() => conditional = !conditional}>
  切换内容
</button>

原理说明

  • ContentB现在直接绑定conditional状态,当conditional变化时会立即销毁/创建,不会受Drawer动画影响。
  • Drawer的显示状态showDrawer与conditional反向同步,当conditional变为true时,showDrawer变为false,触发Drawer的退出动画,动画完成后Drawer才会被销毁。
  • 这样既实现了内容的即时切换,又保留了Drawer的动画效果。

如果需要在Drawer动画结束后执行额外逻辑(比如清理数据),可以监听outroend事件:

<Drawer transition:fly on:outroend={() => {
  // 动画结束后的操作
}}>
  <Component />
</Drawer>

内容的提问来源于stack exchange,提问作者munHunger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 07:18:31