在Vue中主要是通过Vue提供的内置组件<transition></transition>
组件来显示动画。
1.包裹单个元素或者组件
<template> <div> <button @click="isShow = !isShow">toggle</button> <transition name="ydkd"> <h1 v-if="isShow">Content</h1> </transition> </div> </template> <script setup> import { ref } from '@vue/reactivity'; const isShow = ref(true) </script> <style scoped> .ydkd-enter-from, .ydkd-leave-to { opacity: 0; } .ydkd-enter-to, .ydkd-leave-from { opacity: 1; } .ydkd-enter-active, .ydkd-leave-active { transition: all 2s ease; } </style>
2.包裹多个元素或者组件
<template> <div class="container"> <div> <button @click="isShow = !isShow">toggle</button> </div> <transition name="ydkd" mode="out-in" :appear="true"> <h1 class="tip" v-if="isShow">Hello transition</h1> <h1 class="tip" v-else>Hello YDKD</h1> </transition> </div> </template> <script setup> import { ref } from '@vue/reactivity'; const isShow = ref(true); </script> <style scoped> .container { margin: 0 auto; text-align: center; } .tip { display: inline-block; } .ydkd-enter-active { animation: bounce 2s ease; } .ydkd-leave-active { animation: bounce 2s ease reverse; } @keyframes bounce { 0% { transform: scale(0); } 50% { transform: scale(1.2); } 100% { transform: scale(1); } } </style>
细节:
<transition mode="out-in"></transition>
设置mode属性,值有两个。
<transition :appear="true"></transition>
,即默认开启动画,appear的属性值默认为false.
v-enter-from -> v-enter-to 从隐藏到显示
v-leave-to <- v-leave-from 从显示到隐藏
v-enter-active <-> v-leave-active 从元素显示到隐藏 / 从隐藏到显示 的过渡动画效果
图解
当Vue进行模板编译时,发现被<transition></transition>
包裹的元素时,Vue会进行一下处理
1、persisted属性为true,标明为<transition></transition>
代表着当前不会进行 insert/remove元素,会在render层进行跳过。
2、在针对<transition name="ydkd"></transition>
,如果没有设置name,则在源码中会取v。
const { name = 'v', type, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps
3、<transition></transition>
组件包含了许多的钩子函数,判断元素的显示与隐藏时,例如实现原理的第一点,在恰当的时机添加/删除 CSS类名。在源码中会使用到以下函数。
// 添加类名 export function addTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.add(c)) ;( (el as ElementWithTransition)._vtc || ((el as ElementWithTransition)._vtc = new Set()) ).add(cls) } // 移除类名 export function removeTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.remove(c)) const { _vtc } = el as ElementWithTransition if (_vtc) { _vtc.delete(cls) if (!_vtc!.size) { ;(el as ElementWithTransition)._vtc = undefined } } }