Vue封装动画与过度技巧总结

730 阅读1分钟

动画

介绍

image.png

image.png

标签

  1. transition:vue中自带实现动画标签
  2. appear:初次渲染执行,默认false
  3. v-enter-active: 动画进入样式默认名称
  4. v-leave-active: 动画离开样式默认名称
  5. nametransition取别名,替代默认名称,如hello-enter-active

界面

<transition name="hello" appear> 
     <h1 class="title" v-show="show" >hi,动画</h1>
</transition>

方法

// show: true,
onShow() {
   this.show = !this.show
}

样式

<style type="text/css">
.title {
    background-color: aqua;
    padding: 40px;
} 
.hello-enter-active {
    animation: anmiddle 1s linear;
}
.hello-leave-active {
    animation: anmiddle 1s linear reverse;
}
@keyframes anmiddle {
    from{
     transform: translateX(-100%);
    }
    to{
     transform: translateX(0);
    }
}
</style>

简化

  1. 写法一
.big_news{
    transition: all 0.5s;
}
.big_news:hover{
    cursor:pointer;
    transform: scale(1.05);
}
  1. 写法二
.news_button:after {
  position: absolute;
  content: '';
  width: 0;
  height: 2px;
  top: 100%;
  left: 50%;
  background: #5c95e6;
  transition: all 0.5s;
}
.news_button:hover:after {
  left: 0;
  width: 100%;
}

过度

界面

<button type="button"  @click="onShow">按钮</button>
<transition name="hello" appear> 
   <h1 class="title" v-show="show" >hi,动画</h1>
</transition>

方法

// show: true,
onShow() {
   this.show = !this.show
}

样式

.title {
	background-color: aqua;
	padding: 40px;
} 
// 来和去激活状态
.hello-enter-active , .hello-leave-active {
	transition: 1s linear;
}
// 来起点,离开终点
.hello-enter, .hello-leave-to {
	transform: translateX(-100%);
}
// 离开起点,来终点
.hello-leave , .hello-enter-to {
	transform: translateX(0);
}

多元素过度

使用transition-group,key必须加上

<transition-group name="hello" appear> 
        <h1 class="title" v-show="show" :key="1">hi,动画</h1>
        <h1 class="title" v-show="!show" :key="2">hi,多元素动画</h1>
</transition-group>

使用第三方动画库

animate.css

    <!-- 使用  :duration="{ enter: 200, leave: 400 }"  来分别设置 入场的时长 和 离场的时长  -->
    <transition 
        name="animate__animated animate__bounce" 
        enter-active-class="animate__shakeY" 
        leave-active-class="animate__backOutDown" 
        :duration="{ enter: 2000, leave: 400 }"
    >
      <h3 v-if="flag" class="animated">这是一个H3</h3>
    </transition>