Transition

为元素或组件添加进入/离开过渡动画。

Props

ts
interface TransitionProps extends BaseTransitionProps {
  children: View
  mode?: 'out-in' | 'in-out'
}
属性类型默认值说明
childrenView子内容
mode'out-in' | 'in-out'过渡模式
namestring'v'过渡 CSS 类名前缀
appearbooleanfalse是否在初始渲染时应用过渡
cssbooleantrue是否使用 CSS 过渡类
durationTransitionDuration显式指定过渡时长
type'transition' | 'animation' | 'auto''auto'过渡类型

TransitionDuration

ts
type TransitionDuration = number | { enter: number; leave: number }

JavaScript 钩子

属性类型说明
onBeforeEnter(el: Element) => void进入前
onEnter(el: Element, done: () => void) => void进入中
onAfterEnter(el: Element) => void进入后
onEnterCancelled(el: Element) => void进入被取消
onBeforeLeave(el: Element) => void离开前
onLeave(el: Element, done: () => void) => void离开中
onAfterLeave(el: Element) => void离开后
onLeaveCancelled(el: Element) => void离开被取消
onBeforeAppear(el: Element) => void初始渲染进入前
onAppear(el: Element, done: () => void) => void初始渲染进入中
onAfterAppear(el: Element) => void初始渲染进入后
onAppearCancelled(el: Element) => void初始渲染进入被取消

CSS 类名

name'v' 时,会自动应用以下 CSS 类:

阶段类名
进入起始v-enter-from
进入激活v-enter-active
进入结束v-enter-to
离开起始v-leave-from
离开激活v-leave-active
离开结束v-leave-to

可通过自定义类名属性覆盖:

属性说明
enterFromClass进入起始类名
enterActiveClass进入激活类名
enterToClass进入结束类名
leaveFromClass离开起始类名
leaveActiveClass离开激活类名
leaveToClass离开结束类名

示例

CSS 过渡:

tsx
import { Transition, ref } from 'vitarx'

function App() {
  const show = ref(true)

  return (
    <div>
      <button onClick={() => (show.value = !show.value)}>Toggle</button>
      <Transition name="fade">{show.value && <div class="box">Content</div>}</Transition>
    </div>
  )
}
css
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

JavaScript 钩子:

tsx
<Transition
  onEnter={(el, done) => {
    el.style.opacity = '0'
    requestAnimationFrame(() => {
      el.style.transition = 'opacity 0.3s'
      el.style.opacity = '1'
      setTimeout(done, 300)
    })
  }}
  onLeave={(el, done) => {
    el.style.opacity = '1'
    requestAnimationFrame(() => {
      el.style.transition = 'opacity 0.3s'
      el.style.opacity = '0'
      setTimeout(done, 300)
    })
  }}
>
  {show.value && <div>Content</div>}
</Transition>

TransitionGroup

为列表中的元素添加过渡动画,支持移动动画。

Props

ts
interface TransitionGroupProps<T, Tag extends HostElementTag>
  extends
    BaseTransitionProps,
    Omit<ForProps<T>, 'onEnter' | 'onLeave' | 'onBeforeUpdate' | 'onAfterUpdate'> {
  tag?: Tag
  moveClass?: string
  props?: WithProps<Tag>
}
属性类型说明
tagHostElementTag容器标签名
moveClassstring移动过渡的 CSS 类名

参考Transition 详解