作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。


(1)准备好样式:

  • 元素进入的样式:
    1. v-enter:进入的起点
    2. v-enter-active:进入过程中
    3. v-enter-to:进入的终点
  • 元素离开的样式:
    1. v-leave:离开的起点
    2. v-leave-active:离开过程中
    3. v-leave-to:离开的终点

      (2)使用包裹要过度的元素,并配置name属性:

      1. <transition name="hello">
      2. <h1 v-show="isShow">你好啊!</h1>
      3. </transition>

      (3)备注:若有多个元素需要过度,则需要使用:,且每个元素都要指定key值。

Test

  1. <template>
  2. <div>
  3. <button @click="isShow = !isShow">显示/隐藏</button>
  4. <transition name="hello" appear>
  5. <h1 v-show="isShow">你好啊!</h1>
  6. </transition>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. name:'Test',
  12. data() {
  13. return {
  14. isShow:true
  15. }
  16. },
  17. }
  18. </script>
  19. <style scoped>
  20. h1{
  21. background-color: orange;
  22. }
  23. .hello-enter-active{
  24. animation: atguigu 0.5s linear;
  25. }
  26. .hello-leave-active{
  27. animation: atguigu 0.5s linear reverse;
  28. }
  29. @keyframes atguigu {
  30. from{
  31. transform: translateX(-100%);
  32. }
  33. to{
  34. transform: translateX(0px);
  35. }
  36. }
  37. </style>

Test2

  1. <template>
  2. <div>
  3. <button @click="isShow = !isShow">显示/隐藏</button>
  4. <transition-group name="hello" appear>
  5. <h1 v-show="!isShow" key="1">你好啊!</h1>
  6. <h1 v-show="isShow" key="2">尚硅谷!</h1>
  7. </transition-group>
  8. </div>
  9. </template>
  10. <script>
  11. export default {
  12. name:'Test',
  13. data() {
  14. return {
  15. isShow:true
  16. }
  17. },
  18. }
  19. </script>
  20. <style scoped>
  21. h1{
  22. background-color: orange;
  23. }
  24. /* 进入的起点、离开的终点 */
  25. .hello-enter,.hello-leave-to{
  26. transform: translateX(-100%);
  27. }
  28. .hello-enter-active,.hello-leave-active{
  29. transition: 0.5s linear;
  30. }
  31. /* 进入的终点、离开的起点 */
  32. .hello-enter-to,.hello-leave{
  33. transform: translateX(0);
  34. }
  35. </style>

test3

  1. <template>
  2. <div>
  3. <button @click="isShow = !isShow">显示/隐藏</button>
  4. <transition-group
  5. appear
  6. name="animate__animated animate__bounce"
  7. enter-active-class="animate__swing"
  8. leave-active-class="animate__backOutUp"
  9. >
  10. <h1 v-show="!isShow" key="1">你好啊!</h1>
  11. <h1 v-show="isShow" key="2">尚硅谷!</h1>
  12. </transition-group>
  13. </div>
  14. </template>
  15. <script>
  16. import 'animate.css'
  17. export default {
  18. name:'Test',
  19. data() {
  20. return {
  21. isShow:true
  22. }
  23. },
  24. }
  25. </script>
  26. <style scoped>
  27. h1{
  28. background-color: orange;
  29. }
  30. </style>