preface

Vue-router is a key and difficult part of vUE. It is difficult to learn and disable the router at one time. It took me more than one day to sort out the router

What is front-end routing

Simple concept: Mapping between Hash addresses and components

How front-end routing works

  1. The user clicked on the routing link on the page
  2. The Hash value in the URL address bar changes
  3. The front-end route listens for the Hash address change
  4. Render the component corresponding to the current Hash address into the browser

Vue-router Usage procedure

Vue – the router documentation

  1. The installation
npm i vue-router
Copy the code

2. Import routes

import Vue from 'vue'
import VueRouter from 'vue-router'
Copy the code

3. The registered vue – the router

// In vue, you need to call vue.use () to use any plug-in that uses vUE.
Vue.use(VueRouter)
Copy the code

4. Set a matching rule

const routes = [
    {
        path: '/'.// The default hash path
        redirect:'/find' // Redirect to find}, {path: '/find'.component: Find
    },
    {
        // Dynamic parameter transmission mode 1: : Indicates that the dynamic station ID is user-defined
        path: '/My/:id'.component: My,


        // Dynamic parameter transfer mode 2: Enable the props attribute to transfer parameters
        props:true
    },
    {
        path: '/part'.component: Part,
        redirect:'/part/tab1'.// Declare nested child routing rules with the children attribute
        children: [{// Default child route: If the path value of a routing rule in the children array is an empty string, the child route is displayed by default
                // Do not add/after path
                path: 'tab1'.component:Tab1
            },
            {
                path: 'tab2'.component:Tab2
            }
        ]
    },
    {
        path: '/part/:name'.component: Part,
        props: true
    },
    {   // Route 404 Settings
        path: The '*'.component:NotFound
    }
]
Copy the code

5. Instantiate the router

const router = new VueRouter({
    routes,
    mode:"history".// History mode
})
Copy the code

6. The router is deduced

export default router
Copy the code

7. Import a route and mount it

In the main point JS

// Import routes globally
import router from './router'
new Vue({
  router,// Mount the route
 
  render: h= > h(App),
}).$mount('#app')
Copy the code

Route configuration item

Common routing configuration items are as follows:

  1. Path: hash address to be requested

  2. Component: The component to display

  3. Redirect: Specifies a new route address

  4. Children: Uses the children attribute to declare nested sub-routing rules

  5. Name: indicates the name of a route

  6. Props: Route decoupling, a method of route parameter transmission, for dynamic routes

  7. Meta: Indicates the meta information carried by the current route

Vue Routing – Declarative navigation

  1. Vue-router provides a global component, router-link
  2. Router-link essentially ends up rendering as a link to property is equivalent to providing href property (to doesn’t need #)
  3. Router-link provides declarative navigation highlighting (with class names)

Declarative navigation is written inside the Template tag and triggered by the tag

<template>
  <div>
    <div class="footer_wrap">// Declarative navigation renders as a link<router-link to="/find">Found that music</router-link>
      <router-link to="/my">My music</router-link>
      <router-link to="/Part">A friend</router-link>
    </div>
    <div class="top">// Display a placeholder for the component<router-view></router-view>
    </div>
  </div>
</template>
Copy the code

Declare the navigation-class name distinction

Observe the pattern of route nested navigation

  • Router-link-exact -active Specifies the hash value of the URL, which is identical to the href value
  • Router-link-active Hash value in the URL, including the href value of the path

Vue routing – programmatic navigation

Programmatic navigation: by callingJavaScriptIn the form ofAPIThe way to achieve navigation is called programmatic navigation

Instead of using

to create an A tag to define navigation links, we can use the router instance method to write code to do so.

router.push(location, onComplete? , onAbort?)

Note: Inside the Vue instance, you can pass$routerAccess the routing instance. So you can callthis.$router.push.

To navigate to different urls, use the router.push method. This method adds a new record to the history stack, so when the user clicks the browser back button, it returns to the previous URL.

This method is called internally when you click

, so click

is equivalent to calling router.push(…) .

declarative programmatic
<router-link :to="..." > router.push(...)
/ / string
router.push('home')

/ / object
router.push({ path: 'home' })

// Named route
router.push({ name: 'user'.params: { userId: '123' }})

// With query parameters, change to /register? plan=private
router.push({ path: 'register'.query: { plan: 'private' }})
Copy the code

Note: If providedpath.paramsWill be ignored in the example abovequeryThis is not the case. Instead, as in the following example, you need to provide the routenameOr handwritten complete with parameterspath:

const userId = '123'
router.push({ name: 'user'.params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// Params does not work here
router.push({ path: '/user'.params: { userId }}) // -> /user
Copy the code

The same rule applies to the to property of a router-link component.

router.replace(location, onComplete? , onAbort?)

Much like router.push, the only difference is that it does not add a new record to history, but replaces the current history record with its method name.

declarative programmatic
<router-link :to="..." replace> router.replace(...)

router.go(n)

This method takes an integer that means how many steps forward or backward in the history, similar to window.history.go(n).

The sample


// Further forward in the browser record, equivalent to history.forward()
router.go(1)

// Step back to record, equivalent to history.back()
router.go(-1)

// Forward 3 steps record
router.go(3)

// If history is not enough, fail silently
router.go(-100)
router.go(100)

Copy the code

Nested routing

Realize the nesting of components through routing, and then nest second-level routes under the existing first-level routes, which is called route nesting


const router = new VueRouter({
  routes: [{path: '/user/:id'.component: User,
      children: [{// If /user/:id/profile matches successfully,
          // The UserProfile will be rendered in User's 
      
          path: 'profile'.component: UserProfile
        },
        {
          // when /user/:id/posts matches successfully
          // UserPosts will be rendered in User's 
      
          path: 'posts'.component: UserPosts
        }
      ]
    }
  ]
})

Copy the code

Routing and the cords

format

this.$router.push({
    path: "Routing path"
    name: "Route name".query: {
    	"Parameter name": value}params: {
		"Parameter name": value}})// The corresponding route receives $route.params. parameter name Value
// The corresponding route receives $route.query. parameter name Value
Copy the code

Extra caution: Using path automatically ignores params

The query parameter

Parameter transfer Method 1

/ / <! -- jump route with query parameter -->
<router-link :to="`/home/message/detail? id=${m.id}&title=${m.title}`">{{m.title}}</router-link>
Copy the code

Way 2

<! -- jump route with query parameter --><router-link :to="{ path:'/home/message/detail', query:{ id:m.id, title:m.title } }">
{{m.title}}
</router-link>
			
Copy the code
Receive parameters
// The route receives the $route.query. Parameter name{{$route.query.id}}</li><li>{{$route.query.title}}</li>
Copy the code

Params parameters

Methods a

<! -- jump route with params parameter --><router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>
Copy the code

Way 2

<! -- jump route with params parameter --><router-link :to="{ name:'xiangqing', params:{ id:m.id, title:m.title } }">
	{{m.title}}
</router-link>
Copy the code
Receive parameters
// The route receives the $route.params. parameter name{{$route.params.id}}</li><li>{{$route.params.title}}</li>
Copy the code

Route is different from router

$route is the route parameter object, including path, Params, Hash, Query, fullPath, matched, name and other route information parameters.

$Router is an object of VueRouter. Vuue. Use (VueRouter) and the Vue constructor get an instance of the router

Props configuration of routing

Props is the object mode

Value is an object. All key-values in this object are passed to the component in the form of props, and the configuration is passed to the component within the routing rule

const router = new VueRouter({
  routes: [{path: '/promotion/from-newsletter'.component: Promotion,
      props: { newsletterPopup: false}}}])Copy the code

Props is the Boolean mode

Value is Boolean. If true, all params parameters received by the route component are passed to the Detail component as props

const router = new VueRouter({
  routes: [{path: '/promotion/from-newsletter'.component: Promotion,
      props:true}]})Copy the code

Props is the function mode

const router = new VueRouter({
  routes: [{path: '/search'.component: SearchUser,
      props: route= > ({ query: route.query.q })
    }
  ]
})
Copy the code

Vue-router supports hash mode and history mode

Hash mode and history mode are two single-page routing modes:

Hash mode:

The underlying principle is implemented through hashChange, which uses the HASH of URL to simulate a complete URL. The displayed network path will have a “#” number. Although the hash appears in the URL, it will not be included in the HTTP request and has no impact on the back end. So if you change the hash and refresh it, there’s no problem

The history mode:

The underlying principle is replaceState(), pushState(), and history is a glorified hash mode with no “#” in the path. The history API project that relies on Html5 is packaged online because the address has changed. When refreshing, it will request the backend according to the modified address. The backend configuration needs to be processed, and the address access will be mapped

Solution:

Why hashed packaging doesn’t have a problem? This is because the hash mode will go to the index page by default, while the history running code found that no token will go to the login page, but there is only one index page, which requires the cooperation of the back end, depending on the back-end application, but the principle is the same, need the back end to redirect the request to the index page