vue2基础 - transition 过渡动画结合 animate.css和 Velocity.js 的使用

刘高峯
2023-12-01

Vue 在插入、更新或者移除 DOM 时,提供多种不同方式的应用过渡效果。包括以下工具:

  • CSS 过渡和动画中自动应用 class
  • 配合使用第三方 CSS 动画库,如 Animate.css
  • 在过渡钩子函数中使用 JavaScript直接操作 DOM
  • 配合使用第三方 JavaScript 动画库,如 Velocity.js

CSS 动画库 Animate.css

1)如果 Vue 项目需要使用 animate.css 的话,首先进入项目文件夹执行如下命令进行安装:

npm install animate.css -save

使用文档

2)过渡动画的使用示例
template 模板的伪代码

<div>自定义过渡的类名</div>
<button @click="showCustomer = !showCustomer">Toggle render</button>
<transition
  name="flip"
  enter-active-class="animate__animated animate__flipInX"
  leave-active-class="animate__animated animate__flipOutY"
>
  <p v-if="showCustomer">hello</p>
</transition>

Tips:
测试的时候发现 class name和动画class要一致才有效果,如flip,可用 flipInX、flipOutY等。

JavaScript 钩子结合 Velocity.js 库

template模板中的伪代码:

<div>JavaScript钩子</div>
<button @click="showCss4 = !showCss4">Toggle</button>
<transition
  v-on:before-enter="beforeEnter"
  v-on:enter="enter"
  v-on:leave="leave"
  v-bind:css="false"
>
  <p v-if="showCss4">Demo</p>
</transition>

script脚本里面的method定义的方法

beforeEnter: function (el) {
  el.style.opacity = 0;
  el.style.transformOrigin = "left";
},
enter: function (el, done) {
  Velocity(el, { opacity: 1, fontSize: "1.4em" }, { duration: 300 });
  Velocity(el, { fontSize: "1em" }, { complete: done });
},
leave: function (el, done) {
  Velocity(el, { translateX: "15px", rotateZ: "50deg" }, { duration: 600 });
  Velocity(el, { rotateZ: "100deg" }, { loop: 2 });
  Velocity(
    el,
    {
      rotateZ: "45deg",
      translateY: "30px",
      translateX: "30px",
      opacity: 0,
    },
    { complete: done }
  );
},

示例

使用示例

 类似资料: