vue实现fadein
Vue 实现 FadeIn 效果
在 Vue 中实现 FadeIn 效果可以通过 CSS 过渡或动画结合 Vue 的动态特性完成。以下是几种常见方法:
使用 CSS Transition
通过 Vue 的 v-if 或 v-show 控制元素显示,结合 CSS 过渡实现淡入效果。
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition name="fade">
<div v-if="show" class="box">Fade In Effect</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.box {
width: 200px;
height: 100px;
background: #42b983;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用 CSS Animation
通过 Vue 的 transition 组件和 CSS 动画实现更复杂的淡入效果。
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition name="fade">
<div v-if="show" class="box">Fade In Animation</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.fade-enter-active {
animation: fadeIn 0.5s;
}
.fade-leave-active {
animation: fadeIn 0.5s reverse;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.box {
width: 200px;
height: 100px;
background: #42b983;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用第三方库(如 Animate.css)
结合 Animate.css 可以快速实现丰富的淡入效果。
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition
enter-active-class="animate__animated animate__fadeIn"
leave-active-class="animate__animated animate__fadeOut"
>
<div v-if="show" class="box">Animate.css FadeIn</div>
</transition>
</div>
</template>
<script>
import 'animate.css';
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.box {
width: 200px;
height: 100px;
background: #42b983;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
动态控制样式
通过动态绑定样式实现更灵活的淡入效果。

<template>
<div>
<button @click="toggleFade">Toggle</button>
<div
class="box"
:style="{ opacity: opacity, transition: 'opacity 0.5s' }"
>
Dynamic FadeIn
</div>
</div>
</template>
<script>
export default {
data() {
return {
opacity: 0
}
},
methods: {
toggleFade() {
this.opacity = this.opacity === 0 ? 1 : 0;
}
}
}
</script>
<style>
.box {
width: 200px;
height: 100px;
background: #42b983;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
以上方法均可在 Vue 中实现 FadeIn 效果,选择适合项目需求的方式即可。CSS Transition 和 Animation 适合简单场景,第三方库适合快速实现复杂动画,动态绑定样式适合需要精细控制的场景。






