vue中如何实现过渡动画?下面本篇文章给大家介绍一下在vue3中实现过渡动画的两种方法(transition组件和动画库),希望对大家有所帮助!
在实际开发中,为了增加用户体验,经常会使用到过渡动画,而过渡动画在CSS中是通过transition和animation实现的。而在Vue中,Vue本身中内置了一些组件和API可以帮助我们方便的实现过渡动画效果;接下来我们就学习一下。
Vue中中提供了transition组件,该组件可以在下列情况之一的情况下,为元素自动添加进入/离开的过渡效果:
使用方式也比较简单,需要将需要动画展示的组件或者元素使用
立即学习“前端免费学习笔记(深入)”;
如下代码展示了
<template> <button class="btn btn-primary" @click="helloWorldShow = !helloWorldShow"> 显示与隐藏 </button> <br /> @@##@@ <transition> <hello-world v-if="helloWorldShow" msg="【一碗周】过渡动画演示demo" /> </transition> </template> <script setup> import { ref } from 'vue' import HelloWorld from './components/HelloWorld.vue' const helloWorldShow = ref(true) </script> <style> #app { /* more css */ } /* 进入之前和离开后的样式 */ .v-enter-from, .v-leave-to { opacity: 0; } /* 离开和进入过程中的样式 */ .v-enter-active, .v-leave-active { /* 添加过渡动画 */ transition: opacity 0.5s ease; } /* 进入之后和离开之前的样式 */ .v-enter-to, .v-leave-from { opacity: 1; } </style>
代码的运行结果如下图所示:
上面使用的一些class,他们的含义如下所示:
下图是Vue文档中的一张图,完美解释了整个流程
前面我们使用了transition属性实现了组件进入和离开的过渡效果,现在我们可以使用animation属性实现,示例代码如下:
<transition> <hello-world v-if="helloWorldShow" msg="【一碗周】过渡动画演示demo" /> </transition>
css
/* 离开和进入过程中的样式 */ .v-enter-active, .v-leave-active { /* 添加过渡动画 */ transition: opacity 0.5s ease; }
代码运行结果如下:
先看一个问题,当动画在两个元素之间切换的时候,会出现一个问题,复现这个问题的代码如下:
<template> <button class="btn btn-primary" @click="show = !show">显示与隐藏</button> <br /> <transition> <hello-world v-if="show" msg="【一碗周】过渡动画演示demo" /> @@##@@ </transition> </template> <script setup> import { ref } from 'vue' import HelloWorld from './components/HelloWorld.vue' const show = ref(true) </script> <style> /* 省略 */ </style>
运行效果如下:
我们可以看到,在一瞬间两个组件是同时存在的,有的时候我们不需要这种效果,那么我们需要设置
了解这个属性之后,我们将代码修改一下,修改后如下:
<transition mode="out-in"> <hello-world v-if="show" msg="【一碗周】过渡动画演示demo" /> @@##@@ </transition>
现在的运行结果如下:
<transition mode="out-in" appear> @@##@@ </transition>
如果我们在实际的开发中自己去一个一个的编写这些动画序列,那么效率是比较低下的,所以我们经常会用到一些动画库,最常见的就是animate.css。
现在我们就来看那一下如何在Vue中使用animate.css:
安装animate.css
npm i animate.css
引入animate.css
// main.jsimport 'animate.css'
.v-enter-active { animation: fadeInDown 0.5s; } .v-leave-active { animation: fadeOutDown 0.5s; }
他们的优先级会高于普通的类名。
<transition mode="out-in" enter-active-class="animate__animated animate__fadeInDown" leave-active-class="animate__animated animate__fadeOutDown" > @@##@@ </transition>
本篇文章介绍了过渡的基本使用,掌握Vue提供的
除了单个组件的过渡外,Vue还提供了TransitionGroup组件,用于实现多个组件的过渡动画,我们以后介绍。
更多编程相关知识,请访问:编程视频!!
以上就是Vue3中如何实现过渡动画?组件和动画库方法解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号