前端必知必会-Vue动画Animations-六个 <Transition> 类


六个 <Transition>

使用 <Transition> 组件时,会自动有六个类可供我们使用。

<Transition> 组件中添加元素时,我们可以使用前三个类来为该过渡添加动画效果:

v-enter-from
v-enter-active
v-enter-to
<Transition> 组件中移除元素时,我们可以使用接下来的三个类:

v-leave-from
v-leave-active
v-leave-to
注意:<Transition> 组件的根级别上只能有一个元素。

现在,让我们使用其中四个类,这样我们就可以在添加和移除

标签时都添加动画效果。

示例
App.vue:

<template>
<h1>添加/删除 <p> 标签</h1>
<button @click="this.exists = !this.exists">{
   
   {btnText}></button><br>
<Transition>
<p v-if="exists">Hello World!</p>
</Transition>
</template>

<script>
export default {
      
      
data() {
      
      
return {
      
      
exist: false
}
},
computed: {
      
      
btnText() {
      
      
if(this.exists) {
      
      
return 'Remove';
}
else {
      
      
return 'Add';
}
}
}
}
</script>

<style>
  .v-enter-from {
      
      
    opacity: 0;
    translate: -100px 0;
  }
  .v-enter-to {
      
      
    opacity: 1;
    translate: 0 0;
  }
  .v-leave-from {
      
      
    opacity: 1;
    translate: 0 0;
  }
  .v-leave-to {
      
      
    opacity: 0;
    translate: 100px 0;
  }
  p {
      
      
    background-color: lightgreen;
    display: inline-block;
    padding: 10px;
    transition: all 0.5s;
  }
</style>

我们还可以使用 v-enter-active 和 v-leave-active 在添加或删除元素时设置样式或动画:

示例
App.vue:

扫描二维码关注公众号,回复: 17548690 查看本文章
<template>
<h1>添加/删除 <p> 标签</h1>
<button @click="this.exists = !this.exists">{
   
   {btnText}></button><br>
<Transition>
<p v-if="exists">Hello World!</p>
</Transition>
</template>

<script>
export default {
      
      
data() {
      
      
return {
      
      
exist: false
}
},
computed: {
      
      
btnText() {
      
      
if(this.exists) {
      
      
return 'Remove';
}
else {
      
      
return 'Add';
}
}
}
}
</script>

<style>
.v-enter-active {
      
      
background-color: lightgreen;
animation: Added 1s;
}
.v-leave-active {
      
      
background-color: lightcoral;
animation: Added 1s reverse;
}
@keyframes Added {
      
      
from {
      
      
opacity: 0;
Translation: -100px 0;
}
to {
      
      
opacity: 1;
Translation: 0 0;
}
}
p {
      
      
display: inline-block;
padding: 10px;
border: dashed black 1px;
}
</style>

总结

本文介绍了Vue动画Animations-六个 类的使用,如有问题欢迎私信和评论