Transition动画
<template>
<div class="App">
<button @click="isShow = !isShow">切换</button>
<Transition>
<h1 v-show="isShow">哈哈哈哈</h1>
</Transition>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
const isShow = ref(false)
</script>
<style scoped>
.v-enter-from,
.v-leave-to {
opacity: 0;
}
.v-enter-to,
.v-leave-from {
opacity: 1;
}
.v-enter-active,
.v-leave-active {
transition: opacity 1s ease;
}
</style>
动画命名:
<Transition name="change-opacity">
//...
</Transition>
相应类名变化:
.change-opacity-enter-from,
.change-opacity-leave-to {
opacity: 0;
}
animation动画
transition动画相当于只有from和to两个时间节点
animation动画可以划分为0%~100%之间的多个时间节点
@keyframes scaleAnimation {
0% {
transform: scale(0);
}
50% {
transform: scale(1)
}
100% {
transform: scale(2);
}
}
.v-enter-active {
/* transition: all 1s ease; */
animation: scaleAnimation 1s;
}
.v-leave-active {
/* transition: all 1s ease; */
animation: scaleAnimation 1s reverse;
}
过渡模式
默认情况下进入和离开的元素都是在同时开始动画的,故多个元素动画会重叠在一起。
mode:“out-in” 先执行离开动画,然后在其完成之后再执行元素的进入动画
mode:“in-out” 先执行进入动画,然后在其完成之后再执行元素的离开动画
<Transition mode="out-in">
<h1 v-if="isShow">哈哈哈哈</h1>
<h1 v-else>嘿嘿嘿嘿</h1>
</Transition>
初次动画
如果你想在某个节点初次渲染时就执行动画
<Transition appear>
...
</Transition>
组件之间的动画
<template>
<div class="App">
<button @click="isShow = !isShow">切换</button>
<Transition mode="out-in">
<component :is="isShow?'home':'about'"></component>
</Transition>
</div>
</template>
<script>
export default {
components: {
Home,
About
}
}
</script>
<script setup>
import { ref, reactive } from 'vue'
import Home from './components/Home.vue'
import About from './components/About.vue'
const isShow = ref(false)
</script>
<style scoped>
.v-enter-from,
.v-leave-to {
opacity: 0;
}
.v-enter-to,
.v-leave-from {
opacity: 1;
}
.v-enter-active,
.v-leave-active {
transition: opacity 1s ease;
}
</style>
列表元素动画
<template>
<div class="App">
<button @click="addNum">随机位置添加元素</button>
<button @click="removeNum">随机位置删除元素</button>
<button @click="shuffleArr">打乱</button>
<TransitionGroup tag="ul">
<li v-for="item in arr" :key="item">{{ item }}</li>
</TransitionGroup>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { shuffle } from 'underscore'
const arr = ref([0, 1, 2, 3, 4, 5])
function randIndex() {
return Math.floor(Math.random() * arr.value.length)
}
function addNum() {
arr.value.splice(randIndex(), 0, arr.value.length)
}
function removeNum() {
arr.value.splice(randIndex(), 1)
}
function shuffleArr() {
arr.value = shuffle(arr.value)
}
</script>
<style scoped>
.v-enter-from,
.v-leave-to {
opacity: 0;
transform: translateX(-30px);
}
.v-enter-to,
.v-leave-from {
opacity: 1;
transform: translateX(0);
}
.v-move,
/* 对移动中的元素应用的过渡 */
.v-enter-active,
.v-leave-active {
transition: all 1s ease;
}
.v-leave-active {
/* 离开的元素使用绝对定位,脱离文档流 */
position: absolute;
}
</style>