background
Today, when I was writing the page, I saw that the page had no effect and it was just straight in and out without any stylistic appearance. So I wanted to achieve the special effects of switching pages similar to the native app, so I started Google and found that all the solutions on the Internet had their own advantages and disadvantages, so I sorted out the solutions I thought were elegant and recorded.
Implementation difficulties
How to determine whether to advance or backward when switching routes
How to switch left to right animation every time you switch
Solution
We need to define levels for each page, and determine which layer the user enters when switching routes. If the user enters a higher level, do forward animation, and if the user retreats to a lower level, do back animation.
router/
import VueRouter from 'vue-router' import Home from '../components/home/home' import User from '../components/user/user' var router = new VueRouter({ routes:[{ name:'test', path:'/', meta:{index:0},//The index of the meta object is used to define the current route level, from small to large, from low to high component:{ template:'<div>test</div>' } },{ name:'home', path:'/home', meta:{index:1}, component:Home },{ name:'user', path:'/user/:id', meta:{index:2}, component:User }] });
Monitor route jumps, judge the hierarchical relationship between switching pages, and use this to judge the route forward or backward.
<template> <div > <transition :name="transitionName"> <router-view></router-view> </transition> </div> </template> <script> export default { name: 'App', data(){ return { transitionName:'' } }, watch: {//Use watch to listen for changes in $router $route(to, from) { //If the to index is greater than the from index, it is judged as the forward state, otherwise it is the backward state if( > ){ //Set the animation name = 'slide-left'; }else{ = 'slide-right'; } } } } </script>
Write animations of slide-left and slide-right classes
.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); }
Example
CSDN markdown has disabled iframe, if you have a tool to browse the wall, you can clickcodesandbox demo.
The above article is all the content I have shared with you when using vue-router to switch pages. I hope you can give you a reference and I hope you support me more.