效果图
## 实现原理
利用vue的生命周期-钩子函数mounted()
来触发变量修改;
动态的增删类名使得css的过渡动画属性transition
生效。相关可以参考这里:#transform #transition 通过类名实现文字动画过渡
具体逻辑代码
组件 1 - 登录
DOM上使用vue的class绑定一个控制变量ifActiveCustomStyle,
<div :class="{Introduce:true,customStyle:ifActiveCustomStyle}">
data函数返回的对像中初始化该值
export default {
data() {
return {
ifActiveCustomStyle: false,
}
}
}
生命周期中的mounted钩子函数
mounted() {
this.ifActiveCustomStyle = !this.ifActiveCustomStyle
},
相应的css样式
.LoginIn > .Introduce {
background-image: linear-gradient(to bottom right, #4bb0ff, #6149f6);
height: 93px;
auto;
display: flex;
justify-content: center;
align-items: center;
flex-direction:column ;
transition: height 0.3s;
transition-timing-function: ease-in-out;
}
.LoginIn .customStyle{
height: 15em;
}
组件 2 - 注册组件
和组件一大同小异,只有css样式有细微差别。
DOM
<div :class="{ Introduce: true, customStyle: ifActiveCustomStyle }">
data
export default {
data() {
return {
ifActiveCustomStyle: false,
}
}
}
钩子函数
mounted() {
this.ifActiveCustomStyle = !this.ifActiveCustomStyle;
},
相关css
.LoginUp > .Introduce {
height: 15em;
background-image: linear-gradient(to bottom right, #4bb0ff, #6149f6);
auto;
display: flex;
justify-content: center;
align-items: center;
transition: height .3s;
transition-timing-function: ease-in-out;
}
.LoginUp .customStyle{
height: 93px;
}
可能遇到的问题
如果你按照本文的参考,效果没有生效,很可能是因为你使用了vue封装的<transition>
标签。
例如在的你路由出口:
<transition name:'xxx'><router-view></router-view></transition>
那但是又想使用vue的transition怎么办? 我做过尝试,通过路由监听判断,修改总路由出口包裹的
<template>
<div class="index">
<!-- <h3>公元自助预约排队系统</h3> -->
<transition name="transitionName">
<router-view></router-view>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
transitionName: "fade",
};
},
watch: {
$route(to, from) {
const toDepth = to.path;
const fromDepth = from.path;
this.transitionName =
(toDepth == "/" && fromDepth == "/LoginUp") |
(toDepth == "/LoginUp" && fromDepth == "/")
? "custom"
: "fade";
console.log(
"**************来自index.vue,监听路由变化*************",
this.transitionName,
"****************************************"
);
},
},
name: "index",
components: {},
};
</script>
<style scoped>
h3 {
text-align: center;
}
.custom-enter {
}
.fade-enter-active {
transition: opacity 1s;
}
.fade-enter /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
}
</style>
有一种办法是行的通的,但是略微麻烦,那就是写公共transition的css,然后在每个单独的组件中去引入,并给组件包裹上
示例
新建公共transition的CSS
commonTransition.css
.fade-enter-active {
transition: opacity 1s;
}
.fade-enter /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
}
在需要vue的transition的组件中导入css
组件a.vue
<style scoped>
@import "~@/assets/css/commonTransition.css";
</style>
用
组件a.vue
<template>
<transition name="fade">
<div class="Setting">
····
····
</div>
</transition>
</template>