[Vue routing] [vue2 completed]

Routing

        • 28 route route
          • 28.1 Install vue-router
          • 28.2 Small case
          • 28.3 Query mode routing parameter transfer
          • 28.4 parameters
          • 28.5 props optimization
          • 28.6 Destruction and survival of routes
          • 28.6 Two hooks for routing
          • 28.7 Global front route guard
          • 28.8 Global post route guard
          • 29.1 Local route guard
            • 29.1.1 path guard
            • 29.1.2 component guard
28 route route

What is popular today is no longer the previous multi-page application, but a single-page application, which completes the partial refresh of each functional page in one page. Routing in Vue is responsible for switching between pages (switching between components)

28.1 Install vue-router

npm i vue-router@3

Description: Vue2 installation 3 Vue3 installation 4

28.2 Small Case

Table of contents

main.js

Import the js file that configures the router and hand it over to Vue for management.

import Vue from 'vue'
import App from './App.vue'

/* Import router and hand it over to Vue for management*/
import router from './router'
new Vue({<!-- -->
  el: '#app',
  router: router,
  render: h => h(App)
})

index.js

Routing configuration

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
import HeBei from '../components/HeBei'
import HeNan from '../components/HeNan'
const router = new VueRouter({<!-- -->
    routes: [
        {<!-- -->
            //The access path changes, and the component changes accordingly
            path: '/HeBei',
            component: HeBei
        },
        {<!-- -->
            path: '/HeNan',
            component: HeNan
        }
    ]
})
export default router

App.vue

<template>
  <div>
    <div>
        <h1>Province</h1>
        <ul>
            <li><router-link to="/HeBei" active-class="selected">Hebei Province</router-link></li>
            <li><router-link to="/HeNan" active-class="selected">Henan Province</router-link></li>
        </ul>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>
  import HeBei from './components/HeBei.vue'
  import HeNan from './components/HeNan.vue'
  export default {<!-- -->
    name: 'App',
    components:{<!-- -->HeBei,HeNan}
  }
</script>
<style>
.s1 {<!-- -->
            margin-left: 100px;
        }
        .selected {<!-- -->
            background-color: aqua;
        }
</style>

HeBei.vue component

<template>
  <div class="s1">
        <h2>Downtown</h2>
        <ul>
            <li>Shijiazhuang</li>
            <li>Tangshan</li>
            <li>Baoding</li>
            <li>Handan</li>
        </ul>
    </div>
</template>

<script>
export default {<!-- -->
    name:'HeBei'
}
</script>

HeNan.vue component

<template>
  <div class="s1">
        <h2>Downtown</h2>
        <ul>
            <li>Shijiazhuang</li>
            <li>Tangshan</li>
            <li>Baoding</li>
            <li>Handan</li>
        </ul>
    </div>
</template>

<script>
export default {<!-- -->
    name:'HeBei'
}
</script>

Demonstration results:

28.3 Query mode routing parameters

There are three ways to write query parameters:

The first: string form

usage:

To in router-link refers to the path to jump to the component. Configure the path and corresponding component in the routing configuration.

xxx

You can use $route.query to retrieve data from other components

The first way to take out

  • {{$route.query.data name 1}}

The second way to take out

Second type: array form

usage:

Configure the passed parameters in data

//Pass parameters
<li>
      <router-link :to="`/HeNan/city?a1=${anyang[0]} & amp;a2=${anyang[1]} & amp;a3=${anyang[2]}`\ " active- class="selected">Anyang</router-link>
</li>


Configuration in data:
data() {<!-- -->
        return {<!-- -->
            anyang: ['Yindu District 3', 'Long'an District', 'Beiguan District'],
            luoyang:['Luolong District 2','Geely District','Xigong District']
        }
 }

//Note: The method of data retrieval is the same as the first method

The third type: object form

usage:

Directly specify the path and query to to

<li>
    <router-link active-class="selected" :to="{<!-- -->
         //This method of name only supports object form
         name:'anyang',//The premise of using this name attribute is to give the route a name in the js that configures the route.
         //path:'/HeNan/an',
         query:{<!-- -->
              a1:anyang[0],
              a2:anyang[1],
              a3:anyang[2]
                }
     }">
     Anyang
    </router-link>


Configuration in data:
data() {<!-- -->
        return {<!-- -->
            anyang: ['Yindu District 3', 'Long'an District', 'Beiguan District'],
            luoyang:['Luolong District 2','Geely District','Xigong District']
        }
 }
28.4 params

usage:

Configured in routing configuration file

28.5 props optimization

In order to optimize the code above, we can experiment with props to optimize

routing configuration file

props($route){<!-- --> // $route will be automatically passed in the future, which represents the current routing object. Variable names are arbitrary.
    return {<!-- -->
        a1 : $route.params.a1,
        a2 : $route.params.a2,
        a3 : $route.params.a3,
            }
   }

used in components

28.6 Destruction and Survival of Routes

When we switch routes, the route being switched is destroyed. How to ensure that the route being switched is not destroyed? We can do this.

<!-- This tag, if you write it like this, means that all routing components in this tag will not be destroyed when switching. -->
<keep-alive>
    <router-view></router-view>
</keep-alive> -->

<!-- Note: include="component name" means that the specified component will not be destroyed when switching routing components. Reserved status. -->
<keep-alive include="component name">
    <router-view></router-view>
</keep-alive>
28.6 Two hooks for routing

activated and deactivated

These are two life cycle hook functions.

Two life cycle hook functions that are only available in “routing components”.

When the routing component is switched to, activated is called.

When the routing component is removed, deactivated is called.

The purpose of these two hook functions is to capture the activation status of the routing component.

28.7 Global front routing guard

Routing guard, as the name suggests, is an authentication of the visitor’s identity. Access can only be accessed if you have access rights. It is similar to Spring’s filter in Java and the interceptor in springMVC.

  1. This code is written after creating the router and before exposing the router.

  2. The callback in beforeEach is executed once during initialization, and will be called every time before switching any routing component.

  3. callback can be a normal function or an arrow function

    The callback function has three parameters: to from next

    1.from parameter: from is a routing object, indicating where it comes from (which route it is cut from), (starting point)

    2.to parameter: to is also a routing object, indicating where to go (end point)

    3.next parameter: This is a function. After calling this function, it means it is released and can continue to go down.

    4. If you add custom attributes to the routing object, you need to define them in the meta (routing element) of the routing object.

router.beforeEach((to, from, next) => {<!-- -->
    if (verification of authority){<!-- -->
        next()//release
    }else{<!-- -->
        alert('Sorry, you don't have permission!')
    }
})

Here comes the question. When we are actually developing, there are many routes. So if many routes require authentication (verification of permissions), do we also need to use if judgment? The answer is of course no.

We can add such a configuration to the routing. When we judge, we only need to judge whether to.meta.isAuth is true. Unconfigured routes default to undefined (false)

meta : {<!-- -->isAuth : true}
28.8 Global post routing guard

It is executed once during initialization and will be called every time after switching any routing component.

This callback function has two parameters: to, from.

This callback function has no next parameter.

//Written in the js file of the routing configuration, after creating the router object and before exposing the router object.
router.afterEach((to, from) => {<!-- -->
    document.title = to.meta.title || 'Welcome to this system'
})
29.1 Local route guard
29.1.1 path guard

beforeEnter itself is a function, and there is no callback function on the parameters.

//Write into the route object.
beforeEnter(to, from, next){<!-- -->
      if (permission verification){<!-- -->
         next()//release
      }else{<!-- -->
           alert('Sorry, you don't have permission!')
      }
},
29.1.2 component guard

Component guard, the code is written in the component.

Note: Ordinary components will not trigger, only routing components will trigger.

//beforeRouteEnter execution timing: executed before entering the routing component.
beforeRouteEnter(to, from, next){<!-- -->
    console.log("Execute before entering the routing component...")
    next()
},
// beforeRouteLeave execution timing: executed before leaving the routing component.
beforeRouteLeave(to, from, next){<!-- -->
    console.log("Execute before leaving the routing component...")
    next()
}