Vue动画transition

在vue中,显示隐藏,创建移除,一个元素或者一个组件的时候,可以通过transition实现动画。

transition是Vue的组件

  • 进入(显示,创建)

  • v-enter 进入前 (vue3.0是 v-enter-from)

  • v-enter-active 进入中

  • v-enter-to 进入后

  • 离开(隐藏,移除)

  • v-leave 进入前 (vue3.0 是v-leave-from)

  • v-leave-active 进入中

  • v-leave-to 进入后

vue3写法

需求:按钮控制一个盒子的显示和隐藏,需要淡入和淡出

   <!-- 需要做动画的部分用transition包裹 -->
<transition> 
    <div v-show="show" class="box"></div>
</transition>

  <button @click="show=true">显示,创建</button>
  <button @click="show=false">隐藏,销毁</button>
<script>
import { ref } from 'vue'

export default {
  setup () {
    const show = ref(true)  //show来控制盒子显示和隐藏
    return { show }
  }
}
</script>
.box{
  width: 200px;
  height: 200px;
  background: pink;
}
// 淡入 从无到有
.v-enter-from{
  opacity: 0;
}
.v-enter-active{
  transition: all 2s ;
}
.v-enter-to{
  opacity: 1;
}
// 淡出 从有到无
.v-leave-from{
  opacity: 1;
}
.v-leave-active{
  transition: all 2s ;
}
.v-leave-to{
  opacity: 0;
}

如果有多个盒子想使用不同的动画,可以添加name属性,name属性的值替换v即可。

  <transition>
    <div v-show="show" class="box"></div>
  </transition>
  <transition name="x">
    <div v-show="show" class="box" style="background-color: orange;"></div>
  </transition>
  <button @click="show=true">显示,创建</button>
  <button @click="show=false">隐藏,销毁</button>
.box{
  width: 200px;
  height: 200px;
  background: pink;
}
// 盒子一 ----------------------------------
// 淡入 从无到有
.v-enter-from{
  opacity: 0;
}
.v-enter-active{
  transition: all 2s ;
}
.v-enter-to{
  opacity: 1;
}
// 淡出 从有到无
.v-leave-from{
  opacity: 1;
}
.v-leave-active{
  transition: all 2s ;
}
.v-leave-to{
  opacity: 0;
}
// 盒子二-------------------------------
// 宽高变化
.x-enter-from{
  height: 0;
  width: 0;
}
.x-enter-active{
  transition: all 1s ;
}
.x-enter-to{
   height: 400px;
   width: 400px;
}
.x-leave-from{
  height: 400px;
   width: 400px;
}
.x-leave-active{
  transition: all 1s ;
}
.x-leave-to{
  height: 0;
  width: 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_51290060/article/details/129412245