🚀
头像

默永


人生就像骑单车,想保持平衡就得往前走。

vue - 过度与动画

2023-02-03 16:11:35 246 💗 0 @默永

使用transition标签

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

元素进入的样式:

  1. v-enter:进入起点样式
  2. v-enter-active:进入过程中
  3. v-enter-to:进入的终点

元素离开的样式

  1. v-leave:离开的起点
  2. v-leave-avtive:离开过程中
  3. v-leave-to:离开的终点

使用动画写效果

transition标签加入appear属性可以直接加载动画,给transition标签创建name属性时样式class名就要变成name值-enter-active

<transition appear name="hello"></transition>
<style>
    /* 进入时激活动画 */
    .hello-enter-active {
        animation: donghua 0.5s linear;
    }
</style>
<transition>
    <h1 v-show="isShow">你好</h1>
</transition>
<style>
    /* 进入时激活动画 */
    .v-enter-active {
        animation: donghua 0.5s linear;
    }
    /* 离开动画 */
    .v-leave-active {
        animation: donghua 0.5s linear reverse;
    }
    @keyframes donghua {
        from {
            transform: translateX(-100%px);
        }
        to {
            transform: translateX(0px);
        }
    }
</style>

使用过度写效果

<transition name="hello" appear>
    <h1 v-show="isShow">你好</h1>
</transition>
<style>
    h1{
        background-color: orange;
        /* 可以写动画的标签里 */
        transition: 0.5s linear; 
    }
    .hello-enter-active,.hello-leave-active{
        /* 也可以写在这里面 */
        transition: 0.5s linear;
    }
    /* 进入起点、离开的终点 */
    .hello-enter,.hello-leave-to{
        transform: translateX(-100%px);
    }
    /* 进入终点、离开的起点 */
    .hello-enter-to,.hello-leave{
        transform: translateX(0px);
    }
</style>

transition标签里只能使用一个元素,想使用多个元素可以使用transition-group,在使用多个元素动画时需要给动画标签添加key值

<transition name="hello" appear>
    <h1 v-show="isShow">你好</h1>
    <h1 v-show="!isShow">你好</h1>
</transition>

推荐动画库

下载库npm i -S animate.css

网站地址:https://animate.style/

<transition 
    appear 
    name="animate__animated animate__bounce"
    enter-active-class="animate__swing" 
    leave-active-class="animate__backOutUp"
>
    <h1 v-show="isShow">你好</h1>
    <h1 v-show="!isShow">你好</h1>
</transition>
<script>
    import 'animate.css'
</script>
    目录导航