Vue学习之路(七)---transition过渡动画

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29329037/article/details/79124109

vue中过度动画v-if和v-show都可以使用,首先要明白四个状态,v-enter(刚开始进入) ,v-enter-active(进入过程中到进入完毕),v-leave-enter(刚开始离开),v-leave-enter-active(离开过程中到离开),示例图如下
这里写图片描述

好的,弄清楚了这四种状态,然后我们就可以简单的开始transition过渡的实操了,在v-enter-active以及v-leave-enter时这个时候的状态是初始值,比如说opacity这个属性,它的值是1

1.用样式实现简单的过渡效果

App.Vue中
关键代码

//html中
<button @click='move'>实现过渡效果</button>
<transition name='my-trans'>//my-trans样式前缀的名字
  <div v-show='isShow'>这是一段代码</div>
</transition>
//data中
data () {
 isShow : true;
}
//methods中
methods: {
 move () {
   this.isShow = !this.isShow
  }
}
//style中
<style>
.my-trans-enter-active,.my-trans-leave-enter {
  transition: all 1s ease-out;
}
.my-trans-enter {
  transform: translateY(-500px);//从上面进入
}
.my-trans-leave-active {
 transform: translateY(500px);//从下面离开
}
</style>

注意当我们使用v-if 和 v-else 的时候,当两个标签都是统一类型的,vue不会实现动画,这个时候必须加上key,例如

//其他代码同上
//html中
<button @click='move'>实现过渡效果 </button >
<transition name='my-trans' mode='out-in'>//my-trans样式前缀的名字
  <div v-if="isShow" key='1'>这是第一段代码</div>
  <div v-else key='2'>这是第二段代码</div>
</transition>

这个时候可能实现的效果是两段代码会同时出现,显得很难看,只需要在transition上面加上mode=’out-in’(先出后进)就可以了

2.实现组件的过渡

首先我们需要两个组件文件a.vue和b.vue
//a.vue中

<template>
  <div>这是第一个组件</div>
</template>
<script>
 export default {
  data () {
   return {

   }
  }
}
</script>

b.vue中

<template>
  <div>这是第二个组件</div>
</template>
<script>
 export default {
  data () {
   return {

   }
  }
}
</script>

关键代码
在主组件中App.vue中引入两个子组件
import compA from ‘./components/a’
import compA from ‘./components/b’
前面我写过关于如何实现两个组件之间的切换,接下来再写一遍

//html中
<button @click='move'>实现过渡效果</button>
<transition name='my-trans'>//my-trans样式前缀的名字
  <div :is='comName'></div>
</transition>
components : {comA,comB}//引入两个组件
//data中
data () {
 isShow : true,
 comName: 'com-a',
}
//methods中
methods: {
 move () {
   this.isShow = !this.isShow;
   if(this.comName === 'com-a'){//如果是组件a,实现两个组件之间的切换
     this.comName = 'com-b';
   }else {
     this.comName = 'com-a'
   }
  }
}
//style中
<style>
.my-trans-enter-active,.my-trans-leave-enter {
  transition: all 1s ease-out;
}
.my-trans-enter {
  transform: translateY(-500px);//从上面进入
}
.my-trans-leave-active {
 transform: translateY(500px);//从下面离开
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_29329037/article/details/79124109