Skip to content

过渡与动画

Vue 封装的过度与动画:在插入、更新或移除 DOM 元素时,在合适的时候给元素添加样式类名

1.过渡

  1. 准备好样式
  2. 元素进入的样式
    1. v-enter 进入的起点

    2. v-enter-active 进入过程中

    3. v-enter-to 进入的终点

  3. 元素离开的样式
    1. v-leave 离开的起点

    2. v-leave-active 离开过程中

    3. v-leave-to 离开的终点

  4. 使用 <transition> 包裹要过度的元素,并配置 name 属性,此时需要将上面样式名的 v 换为 name
    • 在css中写样式,v前面要加.
css
.hello-enter,            /*进入的起点*/ 
.hello-leave-to {        /* 离开的终点 */
  transform: translate(-100%);
}
.hello-enter-to,    /* 进入的终点 */
.hello-leave {    /* 离开的起点 */
   transform: translate(0);
}
  1. 要让页面一开始就显示动画,需要添加 在transition标签中添加appear属性

  2. 备注:若有多个元素需要过度,则需要使用<transition-group>,且每个元素都要指定 key 值

html
    <transition-group name="hello" appear>
      <h1 v-show="isShow" key="1">你好!</h1>
      <h1 v-show="!isShow" key="2">你好!</h1>
    </transition-group>

2.动画

1.定义过渡元素

html
<transition name="tran">
            <div style="width: 100px; height:100px; background:red"
                v-if="state"></div>
</transition>

2.定义动画

css
@keyframes smallBig {
	0%{
        transform: scale(0);
    }
    50%{
        transform: scale(1.5);
    }
    100%{
        transform: scale(1);
    }
}

3.使用动画

css
.tran-enter-active{
	animation: smallBig .5s;
}
.tran-leave-active{
	animation: smallBig .5s reverse; 
}

3.第三方动画库Animate.css使用

  1. npm (npmjs.com)网站中搜索animate.css

  2. 进网站需要挂梯子(浏览器下载插件(SetupVpn))

  • npm install animate.css 安装动画库

  • import 'animate.css'; script标签引入动画库

  • 给transition标签添加nameanimateanimated animatebounce

html
<transition
    name="animate__animated animate__bounce"
</transition>
  • transition标签添加 enter-active-classleave-active-class 属性,其属性值根据在网站中选择的动画种类,复制填入

html
<transition-group
    name="animate__animated animate__bounce"
    appear
    enter-active-class="animate__rubberBand"
    leave-active-class="animate__backOutUp">
      <h1 v-show="isShow" key="1">你好!</h1>
      <h1 v-show="!isShow" key="2">你好!</h1>
 </transition-group>

MIT Licensed