效果圖
實現原理
利用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;
width: 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);
width: 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>