Recently do a small project, need to do route switching, page slide in slide out of the effect, summed up the idea and method of implementation.
router-view
Wrap the Router-View component with the Transition tag, dynamically add the animation name, and define the transitionName variable in the data.
<transition :name="transitionName">
<router-view></router-view>
</transition>
Copy the code
CSS styles:
.slide-right-enter-active..slide-right-leave-active..slide-left-enter-active..slide-left-leave-active {
will-change: transform;
transition: all 500ms;
position: absolute;
}
.slide-right-enter {
opacity: 0;
transform: translate3d(-100%.0.0);
}
.slide-right-leave-active {
opacity: 0;
transform: translate3d(100%.0.0);
}
.slide-left-enter {
opacity: 0;
transform: translate3d(100%.0.0);
}
.slide-left-leave-active {
opacity: 0;
transform: translate3d(-100%.0.0);
}
Copy the code
Watch monitors route changes
watch: {
// Use watch to monitor $router changes
$route(to, from) {
// If the index to is larger than the index from, the index is in the forward state; otherwise, the index is in the backward state
console.log(to, "to");
console.log(from."from");
if (to.meta.index > from.meta.index) {
// Set the animation name
this.transitionName = "slide-left";
} else {
this.transitionName = "slide-right"; }}},Copy the code
Page in and out effectmeta
In the objectindex
Definition of index
const Help = () => import("./Help.vue");
export default {
path: "/help",
name: "help",
component: Help,
meta: {
index: 8,
},
};
const StaffCard = () => import("./StaffCard.vue");
export default {
path: "/staff-card",
name: "staff-card",
component: StaffCard,
meta: {
index: 9,
},
};
Copy the code
Above, you can achieve the animation effect of the page routing switch. The idea is that CSS will write animations that listen for changes in the route. If the to index is larger than the FROM index, use the forward animation, and vice versa.