preface

Nowadays, mobile apps have higher and higher requirements on user experience. Recently, I have been working on user experience optimization. Because of the need to achieve animation effects similar to APP page switching, baidu and Google search materials are not very complete, so I write documents by myself. By the way, a wave of VueRouter and CSS transition animation knowledge points, welcome interested friends to teach.

Preview the simple demo diagram

The thought that I wrote in the front

  • How to match to the corresponding page to jump to?
  • How to tell if it’s “forward” or “backward” and then use different animations?
  • How to set animation effects for different jumps?

The implementation process

1. The VUE route matches

Create a VUE instance and match the route. Creating a single page application with vue.js + Vue Router is very simple. With vue.js, we can compose an application by combining components. After adding the Vue Router, what we need to do is map the components to routes and tell the Vue Router where to render them.

import Vue from 'vue'
import Router from 'vue-router'Vue.use(Router) // To import Vue and VueRouter using modular programming, you need to call vue.use (Router)Copy the code

The next step is to map the routing components: the (routing) components can be defined by themselves, but of course, to implement the idea of modular componentization, they are imported from other files. The following is a simple “login -> home -> Order -> settlement” page interaction as an example:

import Login from '@/components/login' 
import Index from '@/components/index' 
import PointList from '@/components/pointList/pointList' 
import SettLement from '@/components/pointList/settlement'// Create a router instance and pass in the 'routes' configurationexportDefault New Router({//routes configuration can be passed in directly or defined before use // Each route should map a component, where component can be a component constructor created via vue.extend () or just a component accessory object. Routes: [{path:] routes: [{path:]'/', // Login name:'Login',
      component: Login
    },
    {
      path: '/index'// home page name:'Index',
      component: Index
    },
    {
      path: '/pointList', // order name:'PointList',
      component: PointList
    },
    {
      path: '/settLement', // name of settlement:'SettLement',
      component: SettLement
    }
]
})
Copy the code

$router = $router

In addition to using the global component router-link for click-jump (the equivalent of a button), component routing can also use an instance object owned by the component itself$routerAnd some of its properties to achieve the goal.$routerIs an instance of the VueRouter, equivalent to a global router object. Inside the Vue instance, you can go through$routerAccess a routing instance that contains many properties and child objects, such ashistoryObject, the often used jump link can be called this.$router. Push this.$routerWill push tohistoryAdd a new record to the stack.Copy the code
declarative programmatic
<router-link :to=”…” router.push(…)

Clicking is equivalent to calling router.push(…) (…). The argument to this method can be a string or an object describing the address:

// String router.push('home'// object router. Push ({path:'home' })
// 命名的路由
router.push({ name: 'user'Params: {userId: 123}}) plan=private router.push({ path:'register', query: { plan: 'private' }})
Copy the code

Component route redirect instance: 1.

<router-link :to="{name:'PointList', params: { userId: 123 }}">
      <i class="icon"><img src=".. /assets/point.png" alt=""<span style = "box-sizing: border-box! Important; word-wrap: break-word! Important;"Copy the code
<footer class="version" @click="goPage('Author')">v 1.0</footer> //Js: methods: {goPage(url, param) {this.$router.push({ name: url }); }}Copy the code

Vue $route(read only)

In applications that use vue-router, the route object is injected into each component with a value of this.$route, and the route object is updated when the route is switched. Therefore, route is equivalent to the current route object that is being jumped, from which you can obtain name,path,params,query, etc., that is, it contains the information obtained from the current URL parsing, as well as the route record matched by the URL. Route objects expose the following attributes (common) :

  1. $route.path
A string (string). The path that is equal to the current route object is resolved as an absolute path, such as http://example.com/#/login? Name = aa, enclosing $route. The path/login is displayed, that is, path in the routes configuration when the routes are matched in 1.Copy the code
  1. $route.name String (string). Sometimes it is more convenient to identify a route by a name, especially when linking a route or performing some jump. To link to a named route, pass an object to the to property of the router-link: to link to a named route, pass an object to the to property of the router-link:
<router-link :to="{name:'Order', params: { userId: 123 }}">
</router-link>
Copy the code

The same is true when calling router.push() :

this.$router.push({ name: 'Order', params: { userId: 123 }})
Copy the code
  1. $rout.params object (object). Route forward carries parameters:
this.$router.push({ name: 'Order', params: { userId: 123 }})
console.log(this.$route.params.userId); / / 123Copy the code
  1. $rout.query object (object). Query parameters that can be accessed with:
this.$router.push({name: 'login', query:{name: 'userName'}});
this.$route.query.name; //you //"http://example.com/#/login?name=userName。"
Copy the code
  1. $route.redirectedFrom String (string). Redirect source:
Such as: {path:The '*',redirect: {name: 'hello'}} In this case, access the non-existent route http://example.com/#/a will redirect to hello,Access this in hello.$route.redirectedFrom; Output "/ a".Copy the code
  1. $route. Matched array (array). All the information declared by the current route, from the parent route (if any) to the current route.
  2. $rout.hash String (string). Hash value of the current path.

Vue listens for $route

Watch: {'$route'(to and from) {}}Copy the code

Route changes. The default values in the callback function for the object on which watch listens are newVal,oldVal. The $route attribute is, of course, the concept of to and from.

Vue jumps to the page with router. Push (pass parameters), changes parameters, observes the route changes after the jump, refreshes the page, and sets the animation effect for the process of “from->to”.

The difficulty with this feature is how to get the “previous” and “next” page, that is, how to tell is “forward” or “back”?

Ex. :

// watch $routeDecide which transition to use watch:{'$route'(to, from) {// Suppose you jump from the index page to the pointList page console.log(to); //"/pointList"
      console.log(from); // “/index”
      const routeDeep = ['/'.'/index'.'/pointList'.'/settLement'];
      const toDepth = routeDeep.indexOf(to.path)
      const fromDepth = routeDeep.indexOf(from.path)
      this.transitionName = toDepth > fromDepth ? 'fold-left' : 'fold-right'}},Copy the code

“To” and “from” are the most basic routing objects. They indicate that the page is to be skipped from (from) to (to) another page, respectively. Define a routeDeep array, and sort the routing directory hierarchically (not to mention embedding). In complex single-page applications, the same hierarchy (like multiple navigation buttons on a page) is in any order, and then the next, next and next pages of each navigation… That is, ensure that each “previous page” before the “next page”. ToDepth > fromDepth indicates that the route from the previous page is to the next page. In the same way, you can determine whether to go forward or backward.

Five, the use of transition components in Vue2.0

<transition :name="transitionName">
    <router-view class="view app-view"></router-view>
</transition>
Copy the code
  • Transition has a name attribute that replaces the class name in the Vue hook function.
  • Transition can only have one child and that child must have v-show or V-IF to control whether it is displayed or not.
Transition CSS class names

The name property in transition is used to replace the class name transitionName- in the Vue hook function

  • Transitionname-enter: Defines the start state for entering a transition. Takes effect when the element is inserted and is removed on the next frame.
  • Transitionname-enter -active: Defines the end state of the entry transition. This is applied when the element is inserted and removed after the transition/animation completes.
  • Transitionname-leave: Defines the start state of the leave transition. Takes effect when the exit transition is triggered and is removed on the next frame.
  • Transitionname-leave-active: Defines the end state of the exit transition. This is activated when the leave transition is triggered and removed after the transition/animation completes.
this.transitionName = toDepth > fromDepth ? 'fold-left' : 'fold-right'
Copy the code

In “watch $route”, decide whether to use a different transition effect (fold-left or fold-right) when determining the “forward” and “back” of the page jump.

Vi. Animation effect realization

In the previous topic, after determining the page jump path, set different class names for the two transitions: “fold-left” and “fold-right.” Then, in the CSS, set different animations for the two category names (for example, “swipe left” and “Swipe Right”) :

.fold-left-enter-active {
    animation-name: fold-left-in;
    animation-duration: .3s;
  }
  .fold-left-leave-active {
    animation-name: fold-left-out;
    animation-duration: .3s;
  }
.fold-right-enter-active {
    animation-name: fold-right-in;
    animation-duration: .3s;
  }
  .fold-right-leave-active {
    animation-name: fold-right-out;
    animation-duration: .3s;
  }
Copy the code

The animation property is a shorthand property that sets the six animation properties:

value describe
animation-name Specifies the name of the keyFrame to be bound to the selector.
animation-duration Specifies the time, in seconds or milliseconds, to complete the animation.
animation-timing-function Specifies the velocity curve of the animation.
animation-delay Specifies the delay before the animation begins.
animation-iteration-count Specifies how many times the animation should be played.
animation-direction Specifies whether animations should be played back in turn.
@keyframes fold-left-in { 0% { transform: translate3d(100%, 0, 0); } 100% { transform: translate3d(0, 0, 0); } } @keyframes fold-left-out { 0% { transform: translate3d(0, 0, 0); } 100% { transform: translate3d(-100%, 0, 0); }}Copy the code

Create an animation according to the CSS3@KeyFrames rule. Animation is created by gradually changing one set of CSS styles into another. You can change the CSS multiple times during the animation. You can specify when the change takes place as a “percentage”, or by using the keywords “from” and “to”, which are equivalent to “0%” (the start time of the animation) and “100%” (the end time of the animation). In general, 0% and 100% selectors should always be defined for best browser support. The Transform attribute applies a 2D or 3D transformation to the element. This attribute allows us to rotate, scale, move, or tilt the element. Translate3d (x,y,z) is translate3D (100%, 0, 0). Translate3d (100%, 0, 0) is translate3D (100%, 0, 0) and translate3D (100%, 0, 0) is translate3D.

Seven, write in the back of the pit – blank flash screen when switching between pages

Before optimization:

Solution:

Added the “Position: Absolute;” setting to the page CSS. This time the page is out of the flow of the document, taking up no space, so that the next page is not pushed down, completing a smooth transition. After the optimization:

Temporarily only used this method to solve, there may also be some disadvantages, if there is a better method, welcome to communicate oh.

Finally attach the code address of demo: vue page jump animation effect demo

conclusion

The above is the vUE page jump animation effect function to achieve the 6 steps, that is, the function contained in the 6 big knowledge points, of course, including many expanded knowledge points, endless learning, need to slowly dig deep…