1. Router-link Indicates the forward link of a route and changes the URL
  2. Router-view displays the specific content of the component using the URL,
  3. By defining app. use(router), we can access this.router and this.router and this.router and this.route to realize route skipping and route parameter obtaining
  4. To access the route in the setup function, the userRouter and useRoute functions are called beforehand
    this.$router.push({
        name:'home'.params: { pathMatch: this.$route.path.substring(1).split('/')},query: this.$route.query,
        hash: this.$route.hash
    })
Copy the code
  1. Route matching syntax:
    const routes = {
        {path: '/:id +'} = = = >/ ,/one, /one/two, /one/two/three
        {path: '/:id *'} = = = >/one, /one/two, /one/two/three
        {path: '/user/:id ? '} = = = >The/user / / user/23
    }
Copy the code

When repeatable parameters, such as /first/second/third, use * (0 or more) and + (1 or more) to mark the parameters as repeatable. ? Yes marks the parameter as optional, but cannot be repeated

  1. Nested routines consist of:

    Children is a routing array that implements nested views. If path is “, undefined matching can be implemented in empty nested routines.

    constRoutes = {path:'/user/:id'.component: User,
        children: [{path:'profile'.component: UserProfile,
            },
            {
                path:' '.component: UserHome,
            }
        ]
    }
Copy the code
  1. Programmed navigation

This.$router. Push (‘… ‘)

There are several ways to programmatically navigate:

String path:this.$router.push('/user/profile') object with path:this.$router.push({path:'/user/profile'}) named route with arguments:this.$router.push({name:'user'.params: {id:'12'}}) with query parameters:this.$router.push({path:'/user'.query: {id:'12'}})==> /user? id=12Hash parameters:this.$router.push({name:'/user'.hash:'#team'}) ==> /user#team
Copy the code

Note: With params, only name can be specified, not path. If path is specified, the params parameter is ignored.

Replace the current route:

 this.$router.replace({path:'home'}) = = = >this.$router.push({path:'home'.repalce:true})
Copy the code

History: a historical step forward and backward in history. window.history.go(n);

 router.go(1) is equivalent to router.forward() to move one step forward. router.go(-1) returns a record equivalent to router.back(). router.go(100) move forward100One record, if not so many records, silent failure. The router to imitate thewindowThe history of the API. That is, the router. Push = = =window.history.pushState
 router.replace === window.history.replaceState
 router.go === window.history.go
Copy the code
  1. Named route

Add name in addition to path.

    const routes = [
        {
            path:'/user'.name:'user'.component:User
        }
    ]
Copy the code
  1. Named view:
    const routes = [
        {
            path:'/user'.component: {default,
                LeftSidebar,  // Matches the name attribute in 
      
                RightSidebar
            }
        }
    ]
Copy the code
  1. Redirects and aliases

Redirect Implements route redirection: const routes = [{path:’/home’, redirect:’/’}] Indicates that when the user accesses /home, the URL is replaced with/and matched with /

Alias implementation alias: const routes = [{path:’/’, Component :’homepage’, alias:’/home’}] When a user accesses /home, the URL is still /home, but the user is accessing /

  1. Route component parameters are transmitted

Pass parameters to the routing component through props

 const routes = [
     { 
         path: '/user/:id'.component: User, 
         props: true    // The Boolean mode props is set to true, and this.$route.params is replaced by props
         props: {default:true.sidebar:false}           // Name the view
         props: { newsletterPopup: false }             // Object mode props is an object
         props: route= > ({ query: route.query.q })    // Function mode}]Copy the code
  1. Different historical patterns

The Hash pattern is created by createWebHashHistory(), which has # in the URL, but is bad for SEO. The HTML5 pattern is created by createWebHistory()

14. Navigation Guard:

1. Global Navigation guard, Route exclusive navigation guard, component-level navigation guard 2. Global navigation guards are divided into: global front-guard beforeEach, global parse guard beforeResolve, global afterEach hook 3. Exclusive route guards are divided into: define beforeEach in route configuration 4. Components within the guards are divided into: configurable API (beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave), combination API (onBeforeRouteUpdate/onBeforeRouteLeave)Copy the code
  • [1] Global navigation Guard

    BeforeEach accepts two parameters: to, from to: target to enter from: current navigation Route to leave Return value: false: cancel the current navigation, or reset to the address corresponding to the from route A route address: The third optional argument next, equivalent to router.push(), ensures that next is called exactly once in the navigational guard.Copy the code
    User failed to authenticate to redirect to login page router.beforeEach((to,from,next) = >{
             if(to.name ! = ='Login' && !isAuthenticated) next({ name: 'Login' })
             else next()
         })
    Copy the code
    Router. BeforeResolve will be triggered every time you navigate. After being parsed, the parsed guard will be called correctly. Router.aftereach and router.beforeeach differ in that they do not accept the next parameter, accept a failure parameter. It is used to analyze, change page titles, declare pages and other auxiliary functions. ```js router.afterEach((to,from)=>{ if (! failure) sendToAnalytics(to.fullPath) }) ```Copy the code
  • [2] Routing exclusive guard

BeforeEach is triggered only when entering a route, not params, Query, and Hash. BeforeEach can also define arrays that implement reuse guards for different reasons.

Define beforeEach in routing configurationconst routes = [
        {
            path:'/user'.name: 'user'.component:User,
            beforeEach:(to,from) = >{
                return false
            }
            beforeEach:[removeQueryParams,removeHash]
        }
    ]
    
Copy the code
  • [3] Guards within components

    The configuration apis available are: BeforeRouteEnter, beforeRouteUpdate, beforeRouteLeave Note that beforeRouteEnter can use the next parameter, and the next parameter can access this instance, BeforeRouteUpdate and beforeRouteLeave cannot use the next parameter, but this instance is accessible. Use the composite API: onBeforeRouteUpdate, onBeforeRouteLeaveCopy the code
        const UserDetails = {
            template:'... '.beforeRouteEnter(to,from,next){render the component's route before it is validated by calling next(vm= >{})},beforeRouteUpdate(to,from){called when the current route changes but the current component is reused},beforeRouteLeave(to,from){called when navigation leaves the corresponding route rendering the component},}Copy the code

15. Complete navigation parsing process in 12 steps

1. Navigation is triggered 2. BeforeRouteLeave guard 3 is called in the inactivated component. Call the global beforeEach guard 4. Call the beforeRouteUpdate guard 5 in the reused component. Call beforeEach guard in routing configuration 6. Parse asynchronous routing component 7. Call the beforeRouteEnter guard 8 in the activated component. Call global beforeResolve guard 9. Navigation confirmed 10. Invoke the global afterEach hook 11. Trigger DOM 12 update. Call the callback passed to Next in the beforeRouteEnter guard, and the created component instance is passed in as an argument to the callback.Copy the code
  1. Routing meta information

Meta allows you to attach information to a route, address transition names, access permissions to the current route, and so on. Routing addresses and navigational guards are accessible. Route record: Each route object in the Routes configuration is a route record. If the route record is nested (with children), multiple route records are matched when a route is successfully matched. This. Route. Matched array and this. Route.

  1. Data acquisition

Get after navigation: get data in lifecycle hook, before created navigation: get data in routing guard, beforeRouteEnter

  1. Transition effects

Transition works with meta to achieve transitions in different situations

  1. Scrolling behavior

This feature is only available in browsers that support history.pushState

    const router = createRouter({
        history:createWebHashHistory(),
        scrollbehaivor(to,from,savePosition){
            top:0;
        },
        routes: [...]. })Copy the code
  1. Route lazy loading

JavaScript packages can become very large when packaged to build applications, affecting page loads. Solution 1: Divide the components used by different routing pairs into different code blocks and load the components only when the routes are accessed. Replace static imports with dynamic imports.

Static import:import UserDetails from './user/userDetails'Dynamic import:const UserDetails = () = > import('./user/userDetails')
Copy the code

Solution 2: Package all components into the same asynchronous block by naming them chunk.

Add chunkName to dynamic importconst UserDetails = () = > import(/* webpackChunkName: "group-user" */.'./userDetails.vue')

Copy the code
  1. Navigation fault

Detect navigation failure: navigationResult

    const navigationResult = await router.push('/home')
Copy the code

Aborted: return false in navigation guard cancelled: new navigation is cancelled before navigation is complete. Duplicated: Navigation is blocked and is in target position.

Detect redirection: redirectedFrom

  1. Dynamic routing

    Adding a route: router.addRoute

    router.addRoute({ path:'/about'.component:About })
    Copy the code

    To delete a route: router.removeRoute

    router.removeRoute('about')
    Copy the code

    Add nested routines by

    router.addRoute({ name: 'admin'.path: '/admin'.component: Admin })
    router.addRoute('admin', { path: 'settings'.component: AdminSettings })
    Copy the code

    Viewing Existing Routes

    Router.hasroute () checks if a route exists router.getroutes () retrieves an array of all route records

  2. API to

Js to represents the link of the destination route. The value of to is the object <router-link to="/home"> home </router-link> rendered as <a herf="/home"> home </a> replace router.push(). The difference is that there is no historical record, no retreat. <router-link to="/ ABC "replace></router-link> Custom Whether to wrap the router-link value in the a element, Default: false <router-link to="/home" custom V-slot ="{navigate, href, Route}"> <a :href="href" @click="navigate">{{route.fullPath}}</a> </router-link> active-class aria-current-value when activated The value passed to aria-current when activated, default page exact-active-class link The exact name of the activated class. The createRouter of the corresponding component in the configuration of the route creates an instance of the route. CreateWebHistory takes a routerOptions object representing a list of properties that can be passed. CreateWebHistory creates an HTML5 history schema that takes the optional base argument and must be served using HTTP. file:/// is not an option. CreateWebHashHistory creates a hash history with #, suitable for applications with no host file:/// or when the configuration server cannot use the URL. But it's not good for SEO. (If '#' is provided in base, It won't be ` createWebHashHistory ` add) createWebHashHistory (' # / folder / / app/') / / given url for ` ` / / https://example.com/folder/#/app/ At file:///usr/etc/folder/index.html / / for no ` host ` position, Base is ignored createWebHashHistory ('/iAmIgnored ') / / given url for ` file:///usr/etc/folder/index.html# ` creatememoryHistory NavigationFailureType The type of navigation failure, with three properties, Aborted (4), cancelled(8), Duplicated (16) onBeforeRouteLeave component is triggered when the navigation guard leaves the component, and the component is unloaded. Navigation guard removes onBeforeRouteUpdate component navigation guard is exposed when useLink V-slot API is triggered when currently set to update useRoute returns routing address information must be navigated using useRouter in setUp You must use addRoute in setUp to add a new reason record as a child of the current route. If name exists, delete the previous name. AfterEach adds a navigation hook that executes after navigation. BeforeEach adds a navigation guard, executed before any navigation. BeforeResolve added a navigation guard, Run back history.back() equal to router.go(-1) forward history.forward() equal to router.go(1) getRoutes to get a complete list of routing records before the navigation is resolved RemoveRoute removes existing navigation by name repalce replaces current entry in the history stack, navigates to a new URL Push by pushing an entry in the history stack, Navigate to a new URL name unique name in the routing record fullPath URL encoding is related to the routing address, including PATH, Query, hash matched routing record array ' 'Copy the code

application

Vue permission routing implementation:

  1. Menus are separated from routes and returned by the back end

    The management of the menu is controlled by the back end, such as the newly added menu name and menu icon, which are managed by the back end and configured in the database. Since name is a unique name in the routing record, it is used as the unique key for routing and menu matching.

    {
       name:'login'.path:'/login'.component:r= > require.ensure([], () = > r(require('views/base/Login')), 'Login')}Copy the code

    Note: Name must be defined in order to associate with the route menu returned from the back end. The back end returns an array of menu names for which the current logon has permissions: [‘home’,’finace’,’leader’]

    1. During login, get the menu name array of the current login person returned by the back end through the interface, and then put it in sessionStorage. 2

    
    router.beforeEach((to,from,next) = >{
      // Get the menu array in the cache
      let menuArray = JSON.parse(sessionStorage.getItem('menuArray'))
      // Check whether the current user has available menu array, if yes, through the login page to enter the system
      if(menuArray && menuArray.lengh){
          // Enter if the route to enter is in the menu array, or the faName under the meta tag is in the menu array/faName is the relational page in name. For example, in a query page, the faName of the details page is the route name of the query pageif(menuArray.indexOf(to.name) ! = = -1|| menuArray.indexOf(to.meta.faName) ! = = -1){
              next()
          }else{
              next('/error')}}else{
          // There is no menu of the current system, if no login whitelist
          // Jump to the corresponding page, can be displayed
          if(to.name === 'publicPage'){
              next()
          }
          // If the route to jump to is home
          else if(to.name === 'home') {// Check whether it is single sign-on (SSO)
              if(to.query.token){
                  next()
              }else {
              // If there is no token, it is not single sign-on, skip error page
                  next('/error')}}else{
              // If it is neither a public nor a single sign-on page, skip to the error page
              next('/error')}}})Copy the code
  2. Authentication mechanism: JWT(Json Web Token) authentication mechanism

    JWT composition = Header + Payload + Signature Header: signature algorithm containing the JWT Message body: contains major JWT information, such as the expiration time and major user information. Signature: Ensures that information data is not tampered with

  3. The front and back ends also have a set of permission control design. Namely, user management and permission management. Specific implementation: assign roles to users, each role corresponds to a different menu, according to the user’s role to control the implementation of the menu permissions. Business person, finance person, administrator, executive person.