website

Vue Router is the official route manager of vue.js. Its deep integration with vue.js core makes building single-page applications a breeze. It is easier to understand the meaning of a few words first

  • A singular route can be a single route or a specific route
  • The plural number of routes. It can be understood as a collection of multiple routes
  • Router: a container that manages all routes

The installation

npm install vue-router

The following directory structure

│ App. Vue │ main. Js │ ├ ─ assets │ vue. PNG │ ├ ─ components │ HelloWorld. Vue │ ├ ─ the router │ index. The js │ └ ─ store index, jsCopy the code
// main.js
import Vue from 'vue'
import App from './App'
/ / reference router. Js
import router from './router.js'
Vue.config.productionTip = false

new Vue({
  el: '#app'.// Be sure to inject into vue instance objects
  router,
  components: { App },
  template: '<App/>'
})
Copy the code
// router.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter)

// Import the component page
import Message  from './message.vue';
import News  from './news.vue';

// Define an array of routes
// Here is the path and Component rule.
const routes=[
    {path:'/message'.component:Message},
    {path:"/news".component:News},
    // Nested by
    {
    path:"/language".component:language,
    // Nested child routes are placed in the children array. The child path does not use the/prefix
    children:[
       {
            path: "Java".component: Java,
            // Can store the routing meta message
            meta: { requiresAuth: true}}, {path: "JavaSctipt".component: JavaSctipt
        },
    ]
    },
]

const router=new VueRouter({
    routes
});

// Throw this instance object for external reading and access
export default router
Copy the code

Two ways of routing navigation

  • Declarative navigation (also called tabbed navigation)



jumps to
tag, where the to attribute in the router-link tag is escaped to the href attribute in the A tag.

// :to="{name: 'route name ', [query:{}]}"
<router-link :to="{ name: 'routerName', query: { id: 2021-11-2 }}">Message</router-link>
// :to="{name: 'route name ', [params:{}]}"
<router-link :to="{ name: 'routerName', params: { id: 2021-11-2 }}">Message</router-link>
Copy the code
  • Programmatic navigation

We can use this.$router.push() to implement programmatic navigation, as well as parameter passing

Router. push({name: 'routerName', params: Router.go (n) // router.replace({name: 'routerName', params: {userId: {routerName: 'routerName', params: {userId: {routerName: 'routerName', params: {userId: 123}})Copy the code

Route component parameters are transmitted

1. The params refs

Dynamic routing Routing matches language/Java/: ID

const routes = [{path:"language/Java/:id".nama:"Java".component:"JavaComponent"}]
Copy the code

The router.push() method can take a string path or an object that describes the address.

// String path
this.$router.push('/details/001')
// Object with path
this.$router.push({path'/details/001'})
// Name a route. The name field is required during route configuration
this.$router.push({ name'details'.params: { id'001'}})// Params is ignored if path is provided
this.$router.push({ path'/details'.params: { id'002'}})// Get parameters (watch can be used to monitor router changes)
this.$route.params
Copy the code

2. The query parameter

const routes = [{path:"language/Java".nama:"Java".component:"JavaComponent"}]
Copy the code

The router.push() method can take a string path or an object that describes the address.

/ / way
this.$router.push({path'/details? id=001'})
2 / / way
this.$router.push({ name'details'.query: { id'001'}})// Query params exist simultaneously
this.$router.push({ name'details'.query: { id'001' },params: { id'002'}})Copy the code

3. The hash to participate

With this method, the URL path contains a hash such as /details/001#car. All three methods are valid when using hash (same as query) :

this.$router.push('/details/001#car')
this.$router.push({ path'/details/001'.hash'#car'})
this.$router.push({ name'details'.params: { id'001' }, hash'car'})
/ / receive
this.$route.hash.slice(1)
Copy the code

6. Route configure props

This.$route can be used to get parameters on the component, but it is highly coupled to the route, limiting the coupling of the component. It can only be used to pass characteristic urls

whenpropsSet totrueWhen,route.paramsWill be set to the props of the component.

/ / object
const routes = [{ path'/news/:id'.component: News, props: {name:'fsx'}}]/ / function
const routes = [{ 
    path'/news/:id'.component: News, 
    props(route) = > {
        // The value of return will be used as the value of props
        retuen {}
        }
    }]
Copy the code

Routing guard

Global front and rear guards

const router = new VueRouter({
  routes: [{path: '/foo'.component: Foo,
      children: [{path: 'bar'.component: Bar,
          // a meta field
          meta: { requiresAuth: true }
          // Exclusive guard within the component
          beforeEnter:(to,from,next) = >{}
          beforeRouteLeave:(to,from,next){}
        }
      ]
    }
  ]
})
// Global front-guard (Each means Each route triggers this method)
router.beforeEach(to, from, next){
    // to to that route
    // from where is the route from
    // The next call will jump
}
// Global rear guard
router.afterEach((to, from) = > {
  // ...
)
Copy the code

Complete route

  1. Navigation triggered
  2. Called in a deactivated componentbeforeRouteLeaveThe guards
  3. Call globalbeforeEachThe guards
  4. Called in a reused componentbeforeRouteUpdateGuard (+ 2.2).
  5. Called in the routing configurationbeforeEnter
  6. Parse the asynchronous routing component.
  7. Called in the active componentbeforeRouteEnter
  8. Call globalbeforeResolveGuard (+ 2.5).
  9. Navigation confirmed.
  10. Call globalafterEachHook.
  11. Trigger a DOM update.
  12. callbeforeRouteEnterGuard passnextThe created component instance is passed in as an argument to the callback function.