🤟🏼 冇事来学系--Vue2.0中Vue封装的过度与动画

121 阅读2分钟

「这是我参与2022首次更文挑战的第17天,活动详情查看:2022首次更文挑战

Vue封装的过度与动画

作用:在插入、更新或移除DOM元素时,在合适的时候给元素添加 含有过渡或者动画 的样式类名(操作元素时,Vue会自动帮我们添加指定的样式

写法:

写法:

  1. 准备好样式:
    1. 元素进入的样式 (类选择器):
      1. v-enter:进入的起点
      2. v-enter-active:进入过程中
      1. v-enter-to:进入的终点
    1. 元素离开的样式:
      1. v-leave:离开的起点
      2. v-leave-active:离开的过程中
      1. v-leave-to:离开的终点
  1. 使用包裹要过度的元素,并配置name属性

  2. 使用包裹要过度的元素,并配置name属性

要让哪个元素有过渡效果,就用transition包裹

注意:配置name属性之后,写样式时要用name的属性值来替换掉v,如 name="hello",则样式的选择器要写hello-enter、hello-enter-active等等

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

注意:如果有多个元素要过度,则需要使用包裹这些元素,且每个元素都要指定key值

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

Vue中使用动画

  1. 先定义好一个动画(@keyframes)
  2. 准备样式好,在样式中使用动画
    1. v-enter-active:指定进入过程中的动画
    2. v-leave-active:指定离开过程中的动画
  1. 使用包裹使用动画的元素,并设置name属性
  2. 还可以在中设置appear属性,让元素一进入页面的时候就展示动画
<template>
	<div>
	<transition name="hello" :appear="true">	<!-- 可以简写为只写appear -->
  <h1 v-show="isShow">你好阿!</h1>
	</transition>
	<button @click="isShow=!isShow">显示/隐藏</button>
	</div>
</template>
<script>
	export default {
  	name: 'Test',
    data(){
    	return {
      	isShow: 'true'
      }
    }
  }
</script>
<style>
  h1 {
  	background-color: pink;
  }
  .hello-enter-active {
  	animation: move 0.5s linear;
  }
  .hello-leave-active {
  	animation: move 0.5s linear reverse;		/*进入过程和离开过程动画一样,方向相反*/
  }
  
  /*声明动画*/
  @keyframes move {
    from {
    	transform: translateX(-100%);
    }
    to {
    	transform: translateX(0px);
    }
  }
</style>

Vue中使用过渡

<template>
	<div>
	<transition name="hello" :appear="true">	<!-- 可以简写为只写appear -->
  <h1 v-show="isShow">你好阿!</h1>
	</transition>
	<button @click="isShow=!isShow">显示/隐藏</button>
	</div>
</template>
<script>
	export default {
  	name: 'Test',
    data(){
    	return {
      	isShow: 'true'
      }
    }
  }
</script>
<style>
  h1 {
  	background-color: red;
  }
  /* 进入的起点、离开的终点 */
  .hello-enter-from, .hello-leave-to {
		transform: translateX(-100%)
  }
  
  .hello-enter-active, .hello-leave-active {   /* 把过渡设置到过程中 */
  	transition: all 0.5s linear 
  }
  
  /* 进入的终点、离开的起点 */
  .hello-enter-to, .hello-leave-from {
		transform: translateX(0)
  }
  
</style>

跋尾

本篇内容就到这里了~ 我是Zeus👩🏻‍🚀来自一个互联网底层组装员,下一篇再见! 📖