preface

The content of the article may not be comprehensive, but it is a lot to read slowly. I spent a long time organizing and sharing my thoughts, hoping to help you. However, there will inevitably be typing mistakes or misunderstanding points. If you find them, please tell me [email protected] by email. I will timely modify them.

Vue-router Manages routes

reference

router.vuejs.org/zh/

1.SPA VS MPA

  • SPA: Single page application

    • iframe

    • AMD/CMD + packaging tools

    • The professional routing management module vue-router/React-router-dom

  • MPA: Multi Page application Multi page application

2. Basic overview of vue-Router

download

$ npm i vue-router
OR
$ yarn add vue-router
Copy the code

implementation

1.const router = new VueRouter({
2.  mode: 'history | hash (default)'.3.  routes: [...]
4.})
Copy the code
  • HASH mode uses the HASH of a URL to simulate a complete URL, so that when the URL changes, the page does not reload, depending on different values, render different data for the specified DOM position;

  • The HISTORY mode leverages H5’s HISTORY API to make sure urls look like normal urls and not as ugly as in HASH mode! However, this approach requires the server to support and handle the requested URL (to prevent page refresh, because the address does not exist caused by 404 errors).

1.window.history.back() / window.history.go(- 1) : the fallback2.window.history.forward() / window.history.go(1Forward) :3.window.history.length looks at the number of page records in the history stack4.
5.history.pushState(state, title, url|? XXX = XXX) : Add and activate a history entry (but there is no jump to the page, or the browser does not reload the page until it is refreshed again)6.History. replaceState(state, title, URL) : Modifies the currently active history entry7.window.onpopstate=function(ev){
8.    //=> Listen for changes in active history entries
9.}
Copy the code

3. Basic use of vue-Router

Configure the routing table based on product requirements

1.import Router from 'vue-router';
2.Vue.use(Router);
3.export default new Router({
4.    mode:'xxx'.5.    //=> Level-1 route
6.    routes:[{
7.        path:'/'./ / = > routing path (late need to jump and matching, for example: < the router - link to = '/' > or: to = '{path:'/'} ')
8.        name:'xxx'./ / = > named routing (late can be based on the < the router - link: to = '{name:' XXX '} '> jump)
9.        props:true.//=> If there is a dynamic route to pass parameters, pass the parameter information directly to the component as an attribute, for example: $router. Push ('/list/teacher/1000'); / /list/:type/:id = props:['type','id']; Otherwise, you can get the passed argument based on this.$router.params
10.        //component: XXX, //=> Render component
11.        //component:_=>{
12.            //return import('xxx'); //=> Returns an instance of promise (internally holding a module from parsing and compiling xxx.vue)
13.        / /},
14.        component:{
15.            //=> Can also be a single object. It is possible to use two < router-views > at the same time in a project. In this case, set name=' XXX 'to render multiple components based on different names in the routing table
16.            default:xxx,
17.            view2:xxx
18.        }
19.}, {20.        path:'/home'.21.        component:xxx,
22.        //=> Secondary route
23.        children:[{
24.            path:' '.25.            //=> Route redirection
26.            //redirect:'/home/list',
27.            //redirect:to=>'/home/list',
28.            redirect:{
29.                path:'/home/list'.//=> or name=' XXX 'to jump
30.                params:{xxx:xxx}, //=> Parameter information can be transmitted
31.            }
32.}, {33.            path:'/home/add'.//=> can also be written as path='add'
34.            component:xxx
35.        }]  
36.}, {37.        //=>404 page processing can also be redirected
38.        path:The '*'.39.        component:ErrorComponent
40.    }]
41.});
42.
43.-----------------------------------------
44.import router from './router';
45.new Vue({
46.    router,
47..48.})
Copy the code

Second, build the routing view container (named view)

1.<router-view></router-view>
2.<router-view name='view2'></router-view>
Copy the code

Finally realize route jump and parameter transfer (programmatic navigation)

1.<router-link to='/xxx'> < / router - the link > 2. / / = > pass parameters 3. < the router - link: to = '{name:' XXX ', params: {XXX, XXX}} "> < / router - the link > 4. 5. / * programmatic navigation: */ 6.this.$router. Push ('/ XXX '); 7.this.$router.push({name:'xxx',params:{id:100}}); //=>/xxx/100 8.this.$router.push({path:'/xxx/100'}); 9. This $router. Push ({path: '/ XXX, query: {id: 100}}); //=>/xxx? $router. Query. Id 10. This.$router. Go (-1); 11...Copy the code

Dynamic routing

1.export default new Router({
2.    routes:[{
3.        path:'/xxx/:n/:m'
4.    }]
5.})
6.
7.this.$router.push('/xxx/100/200');
8.
9.this.$router.params = {
10.    n:100.11.    m:200
12.}
Copy the code

4. Navigation guard (route permission verification)

Navigation indicates that the route is changing

  • Global guard (written at end of routing table)
1.//=> Global front-guard
2.router.beforeEach((to,from,next) = >{
3.    //=>to: indicates the route to be entered
4.    //=>from: indicates the route to be left
5.    //=>next() : goes to the next hook in the pipe
6.    //=>next(false) : Terminates current navigation
7.    //=>next('/ XXX ') : next('/ XXX ')
8.});
9.
10.//=> router.beforeresolve Global resolver guard (resolver guard is invoked before navigation is confirmed and after all components within guard and asynchronous route component have been resolver)
11.
12./=> Global post-hook (no next)13.router.afterEach((to, from) = > {
14.  // ...
15.});
Copy the code
  • Route exclusive guard
1.const router = new VueRouter({
2.  routes: [
3.    {
4.      path: '/xxx'.5.      component: xxx,
6.      beforeEnter: (to, from, next) = > {
7.        // ...
8.      }
9.    }
10.  ]
11.})
Copy the code
  • Component internal guard
1.const xxx = {
2.  template: `... `.3.  beforeRouteEnter (to, from, next) {
4.    // called before the corresponding route to render the component is confirmed
5.    / / no! Can!!!! Get component instance 'this'
6.    // Because the component instance has not been created before the guard executes
7.  },
8.  beforeRouteUpdate (to, from, next) {
9.    // Called when the current route changes but the component is being reused
10.    // For example, for a path /foo/:id with dynamic parameters, when jumping between /foo/1 and /foo/2,
11.    // Since the same Foo component will be rendered, the component instance will be reused. And the hook will be called in that case.
12.    // Access component instance 'this'
13.  },
14.  beforeRouteLeave (to, from, next) {
15.    // called when navigating away from the component's corresponding route
16.    // Access component instance 'this'
17.  }
18.}
Copy the code

Complete navigation parsing process

1. Navigation is triggered.

2. Call leave guard in the deactivated component.

3. Call the global beforeEach guard.

4. Call the beforeRouteUpdate guard in the reused component.

5. Invoke beforeEnter in the route configuration.

6. Parse the asynchronous route component.

7. Call beforeRouteEnter in the activated component.

8. Invoke the global beforeResolve guard.

9. Navigation is confirmed.

10. Call the global afterEach hook.

11. Trigger DOM updates.

12. Call the callback passed to Next in the beforeRouteEnter guard with the created instance