(Vue CLI) IV. route advancement (secondary route & route lazy loading & scoped & SASS) + V. route cache (keep alive & activation / deactivation life cycle of routing components)

Time:2022-5-11

4、 Advanced routing

1. Routing mode

There are two routing modes:hashMode (default) andhistorypattern.
hashMode: the principle of anchor link is used to realize the jump of routeVery good compatibility; The disadvantage is that the path has#No, it’s not beautiful enough.
historyMode: the built-in history object in the browser is used to jump the routeIncompatible with older browsers, will refreshLost routing information

const router = new VueRouter({
  mode:'hash',
  routes
})

2. Routing meta information

metaOption: meta information used to configure routes. The contents are user-defined and used to configure route data.

{
    path:'/',
    name:'home',
    meta:{
        Title: 'home page',
        //You can configure the access permission of the route in the route meta information
        roles:['admin','vip','user']
    },
    //Lazy loading of routing components
    component:()=>import('../pages/Home.vue'),
}

3. Navigation guard

vue-routerThe navigation guard provided is mainly used to guard the navigation by jumping or canceling. In fact, navigation guard is some hook functions in the process of route jump.
(1) Front guard — before route jump
userouter.beforeEachRegister a global front guard.
Before each route jump, it will be intercepted, and the next method indicates the next step.
Generally, some permission verification operations are performed here.
to: return the routing information of where to go
from: return routing information from where
nextMethod: for jump

router.beforeEach((to,from,next)=>{
  //Get the permissions of the currently logged in user saved in the browser's cache
  let role = sessionStorage.getItem('role')
  //Verify user access
  if(to.meta.roles && to.meta.roles.includes(role)){
    //The next () method indicates to continue the downward execution
    next()
  }
})

(2) Post guard — route jump completed
userouter.afterEachRegister a rear guard. Usually, you can modify some pages here

router.afterEach((to,from)=>{
  //Configure the title of the current page
  document.title = to.meta.title
})

(“) ~ → everything here is in the routing configuration file router / index JS operation configuration

4. Nprogress loading progress bar

nprogressIs the progress bar that appears at the top of the browser when the page jumps.

(1) Installation
npm install nprogress

(2) Import

//Import nprogress
import NProgress from "nprogress";
//Import nprogress的样式
import "nprogress/nprogress.css";

(3) Used in navigation guard

//Navigation guard
// 1. Route pre guard -- before route jump
router.beforeEach((to, from, next) => {
  //Start loading
  NProgress.start();
  //Usually: some permission verification operations will be done here
  next();
});
// 2. Route post guard -- route jump completed
router.afterEach((to, from) => {
  //Usually: you can modify some pages here
  document.title = to.meta.title;
  //End loading
  NProgress.done();
});

5. Secondary routing

You need to define the primary routing component first and determine which component is configured with secondary routing. Add the children keyword to the configuration rules of that component and configure the rules according to the configuration method of primary routing.

{
    path: '/one',
    name: 'One',
    component: ()=>import('@v/One.vue'),
    meta:{
      title:'One',
      roles:['admin']
    },
    //Define the secondary routing information of one
    children:[
      {
        path:'nj',
        name:'nj',
        //Import components by lazy loading
        component:()=>import('../views/city/Nj.vue'),
        meta:{
          Title: 'Nanjing'
        }
      },
      {
        path:'sz',
        name:'sz',
        component:()=>import('../views/city/Sz.vue'),
        meta:{
          Title: 'Shenzhen'
        }
      }
    ]
  },

App.vue

<router-link to="/">Home</router-link> |
<router-link to="/one">One</router-link> |
<router-link to="/two">Two</router-link> |
<!--  This route view matches the first level route -- >
<router-view></router-view>

One.vue

< router link to = "/ one / NJ" > Nanjing < / router link >| 
< router link to = "/ one / SZ" > Shenzhen < / router link >|
<!--  The route view here matches the secondary route of one -- >
<router-view></router-view>

6. Route lazy loading

Lazy loading of routing is adopted to load routing components to improve the performance of the first screen. The home page component loads faster in order to give customers a better experience.
Lazy loading simply means delayed loading or on-demand loading, that is, loading when needed.
component:()=>import('../pages/Home.vue')

7. Lazy loading of routing packets

Sometimes we want to package all components under a route in the same asynchronous block. You only need to use the name chunk and a special annotation syntax to provide chunk name.
The routing component is loaded lazily. Add the following comments in the component attribute,
Where “a” is the group label, and the same comments will be added to which pages need the same group.
component:()=>import( /* webpackChunkName: "a" */ '../pages/News.vue')

component: ()=>import(/* webpackChunkName: "a" */'../views/Home.vue')
component: () => import(/* webpackChunkName: "a" */'../views/About.vue')
component: () => import(/* webpackChunkName: "b" */'../views/One.vue')
component: () => import(/* webpackChunkName: "b" */'../views/Two.vue')

8.scoped

Add the scoped attribute to the style tag to indicate the local style. The style defined in it is only valid in the current component. In the global component of app, it is the global style and is usually not scoped

<style scoped>
    ....
</style>

9.sass

Sass is a CSS preprocessor.
Using sass, you can define nested styles, which greatly saves CSS code,
Sass can be used to define variables and styles.
use$redTo definered, and then use it where the color is used below$red, laterUnified modification
(1) Installation
npm install sass [email protected] -D
(2) Use

<div>
    <h2>One</h2>
    <div>
      Jiangsu Province
      <div>
        Nanjing Province
        <div>
          yuhuatai district 
          < div > saihongqiao Street < / div >
        </div>
      </div>
    </div>
    <h3>The duck blood fans in Nanjing are really delicious</h3>
    <p>The salted duck in Nanjing is really delicious</p>
</div>
<style scoped lang="scss">
$red:darkred;
.about{
  border: 1px solid black;
  padding: 5px;
  h2{
    color:black;
  }
  h3{
    color: $red;
  }
  p{
    color: $red;
  }
  .province{
    color: $red;
    font-size: 30px;
    .city{
      color: green;
      font-size: 25px;
      .district{
        color: blue;
        font-size: 20px;
        .street{
          color: orange;
          font-size: 15px;
        }
      }
    }
  }
}
</style>

10.less

Less is also a CSS preprocessor. The symbol of the variable defined in less is@
(1) Installation
npm i [email protected] -D
npm i [email protected] -D
(2) Use

<style scoped lang="less">
@red:darkred;
.one {
  border: 1px solid black;
  padding: 5px;
  h2{
    color:black;
  }
  h3{
    color: @red;
  }
  p{
    color: @red;
  }
  .province{
    color: @red;
    font-size: 30px;
    .city{
      color: green;
      font-size: 25px;
      .district{
        color: blue;
        font-size: 20px;
        .street{
          color: orange;
          font-size: 15px;
        }
      }
    }
  }
}
</style>

5、 Route cache

1. Keep alive component

keep-alive: used to cache routing components. By default, all open components will be cached.
If you need to specify which components to cache, use theincludeProperty, which can be passed to an array in which the name of the component is defined.
:includeProperty is bound in the form of an array, and the binding name is in each componentnameName of
Function: through routing cache, the switching between components can save the state of the last component, rather than having to operate again after switching.

<keep-alive :include="['Two','Three']">
  <router-view/>
</keep-alive>
2. Two unique life cycles of routing components

When the routing component adopts caching,createdandmountedThese two life cycle functions will only be executed for the first time; alsodestroyedThis lifecycle function does not execute.
At this time, the following two life cycle hooks are usually used.
Routing component activation state lifecycle function
activated(){}
Routing component deactivation state lifecycle function
deactivated(){}

Note: only when the component is in<keep-alive>If it is switched within the, there will beactivatedanddeactivatedThese two hook functions.

//Routing component activation state lifecycle function
    activated() {
        console. Log ('routing component activation ');
        //Start timer
        this.timer = setInterval(()=>{
            this.count++
        },1000)
    },
    //Routing component deactivation state lifecycle function
    deactivated() {
        console. Log ('route component deactivation ');
        clearInterval(this.timer)
    }