Loading

Vue2 动画与过渡

概述

Vue 为我们优化了 CSS 动画在 Vue 中的使用,帮助我们在使用动画的时候更加的得心应手。

使用 CSS 动画完成 Vue 动画

<template>
  <div id="app">
    <button @click="isShow = !isShow">进入/离开</button>
    <transition name="hello" appear>
      <h1 v-show="isShow">你好</h1>
    </transition>
  </div>
</template>

<script>
  export default {
    name: "App",
    data() {
      return {
        isShow: true
      }
    }
  }
</script>

<style scoped>
  h1 {
    background-color: pink;
  }

  .hello-enter-active {
    animation: brokyz 0.3s ease;
  }

  .hello-leave-active {
    animation: brokyz 0.3s ease reverse;
  }

  @keyframes brokyz {
    from {
      transform: translateY(10px);
			opacity: 0;
    }
    to {
      transform: translateY(0px);
			opacity: 1;
    }
  }
</style>

transition 标签

在 Vue 中,我们需要将需要添加动画效果的元素使用transition标签进行包裹。

name 属性:用于控制标签中元素所使用动画的名字。比如如果指定 name="hello",那么就会使用.hello-xxxx这个定义过的动画。如果什么都不指定,那默认使用.v-xxxxx

appear 属性:用于控制页面加载时是否使用动画。如果为 true,则页面加载时使用动画。

transition 标签只能渲染一个元素,如果有其它元素需要写道一个 div 中,但是这样操作后就无法通过 v-if 等操作互斥显示。

transition-group 标签可以渲染多个标签,但是需要给指定 key 属性才可,否则报错。

Vue 的动画 CSS 名

  1. .v-enter-active:元素进入时的动画。
  2. .v-leave-active:元素离开时的动画。

使用 CSS 过渡完成 Vue 动画

<template>
  <div id="app">
    <button @click="isShow = !isShow">进入/离开</button>
    <transition name="hello" appear>
      <h1 v-show="isShow">你好</h1>
    </transition>
  </div>
</template>

<script>
  export default {
    name: "App",
    data() {
      return {
        isShow: true
      }
    }
  }
</script>

<style scoped>
  h1 {
    background-color: pink;
    border-radius: 5px;
		/* 添加过渡效果 */
    transition: 0.5s ease;
  }
  /* 进入的起点  */
  .hello-enter,
  .hello-leave-to {
    transform: translateY(20px);
    opacity: 0;
  }
  /* 进入的终点 */
  .hello-enter-to,
  .hello-leave {
    transform: translateY(0);
    opacity: 1;
  }

  /* 由于进入的起点和离开的终点相同,进入的终点和离开的起点相同所以合并到一起 */
  /* .hello-leave {
    transform: translateY(0);
		opacity: 1;
  }
  .hello-leave-to {
    transform: translateY(20px);
		opacity: 0;
  } */
</style>

使用第三方动画

推荐使用 animate.css

安装

npm i animate.css

在需要使用的组件中导入动画库

import 'animate.css'

之后根据,官网进行使用。如:

<transition-group
      appear
      name="animate__animated animate__bounce"
      enter-active-class="animate__fadeInRight"
      leave-active-class="animate__fadeOutLeft"
    >
</transition-group>
posted @ 2022-10-03 13:29  brokyz  阅读(175)  评论(0编辑  收藏  举报