Vue.js official routing manager takes you to get started quickly

Introduction to Vue router

Routing is divided into front-end routing and back-end routing

Back end Routing: usually, users send URL requests. The server intercepts requests according to different URLs. The server returns different pages

Front end Routing: the front end returns different pages according to different requests. In single page applications, because most of the page structure is fixed and only a small part needs to be changed, it is more suitable for front-end routing

Vue Router yes Vue.js (opens new window) The official routing manager. It and Vue JS core deep integration makes it easy to build a single page application. The functions include:

  • Nested routing / view tables
  • Modular, component-based routing configuration
  • Routing parameters, queries, wildcards
  • Based on Vue View transition effect of JS transition system
  • Fine grained navigation control
  • Links with automatically activated CSS class es
  • In ieml9 or HTML5, auto degraded mode
  • Custom scroll bar behavior

start

Direct reference

Vue must be introduced first JS because router JS depends on Vue js

    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.4.3/vue-router.min.js"></script> 

Npm installation

npm install vue-router

If you use it in a modular project, you must pass Vue Use() explicitly installs the routing function:

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

Vue.use(VueRouter)

Routing instance

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.4.3/vue-router.min.js"></script> 
</head>
<body>
    <div id = "app">
        <router-link to = "/user">User</router-link>
        <router-link to = "/register">Register</router-link>

        <!-- Route placeholder -->
        <router-view></router-view>
    </div>
    
</body>
</html>
<script>
    const User = {
        template: '<div>User assembly</div>'
    }

    const Register = {
        template:'<h1>Register assembly</h1>'
    }

    //Create routing instance object
    const router = new VueRouter({
        //All routing rules
        routes:[
            {path:'/user',component:User},
            {path:'/register',component:Register}
        ]
    })

    const vm = new Vue({
        el:'#app',
        data:{},
        //Mount routing instance object
        // router:router
        router
    })
</script>

Dynamic route matching

We often match multiple routes with one component. For example, we have a User component. For all users with different ID S, we need to use this component to render. Then, we can use "dynamic segment" in the routing path of "Vue router" to achieve this effect:

const User = {
  template: '<div>User</div>'
}

const router = new VueRouter({
  routes: [
    // Dynamic path parameters start with a colon
    { path: '/user/:id', component: User }
  ]
})

Now, things like / user/foo , and / user/bar , will map to the same route.

A path parameter is marked with a colon:. When a route is matched, the parameter value will be set to {this$ route. Params, which can be used within each component. Therefore, we can update the template of # User # and output the ID of the current User:

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}

You can set multiple "path parameters" in a route, and the corresponding values will be set to $route Params. For example:

patternMatching path$route.params
/user/:username/user/evan{ username: 'evan' }
/user/:username/post/:post_id/user/evan/post/123{ username: 'evan', post_id: '123' }

Except $route In addition to params , the $route , object also provides other useful information, such as $route Query (if there are query parameters in the URL), $route Hash # wait.

Nested Route

Nested routing refers to the situation of nested routing within a route. One of the most common application scenarios is the file directory tree: clicking the primary directory will pop up the secondary directory below it, and clicking the secondary directory will pop up the tertiary directory below it.

Next, the app created in the previous section:

<div id="app">
  <router-view></router-view>
</div>
const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}

const router = new VueRouter({
  routes: [{ path: '/user/:id', component: User }]
})

The < router View > here is the top-level exit, rendering the components matched by the highest-level route. Similarly, a rendered component can also contain its own nested < router View >. For example, add a < router View > in the template of the User component:

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

To render components in nested exits, you need to use the # children # configuration in the parameters of # vueroter #:

const router = new VueRouter({
  routes: [
    {
      path: '/user/:id',
      component: User,
      children: [
        {
          // When / user/:id/profile matches successfully,
          // The UserProfile will be rendered in the User's < router View >
          path: 'profile',
          component: UserProfile
        },
        {
          // When / user/:id/posts match successfully
          // UserPosts will be rendered in User's < router View >
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

Note that nested paths starting with / are treated as root paths. This allows you to make full use of nested components without setting nested paths.

You will find that the children configuration is an array of routing configurations like the routes configuration, so you can nest multiple routes.

At this time, based on the above configuration, when you access / user/foo , the exit of User , will not render anything, because there is no matching sub route. If you want to render something, you can provide an empty sub route:

const router = new VueRouter({
  routes: [
    {
      path: '/user/:id',
      component: User,
      children: [
        // When / user/:id matches successfully,
        // UserHome will be rendered in User's < router View >
        { path: '', component: UserHome }

        // ... Other sub routes
      ]
    }
  ]
})

Programming navigation

Within the Vue instance, the routing instance can be accessed through $router, so we can also write code to call the method of the router instance to realize routing.

The following lists the commonly used example methods in router:

  • router.push(location, onComplete?, onAbort?) Navigate to a new address.
  • router.go(n) specify the number of steps forward or backward in the history record.
// character string
router.push('home')
 
// object
router.push({ path: 'home' })
 
// Named route
router.push({ name: 'user', params: { userId: '123' }})
 
// With query parameters, it becomes / register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
 
// If path is provided, the params parameter will be ignored, for example:
router.push({ path: '/user', params: { userId }}) // -> /user
 
// A step forward in the browser record is equivalent to history forward()
router.go(1)
 
// One step backward is equivalent to history back()
router.go(-1)

Named route

Sometimes, it is more convenient to identify a route by a name, especially when linking a route or performing some jumps. When creating a Router instance, you can set the name of a route in the route configuration.

const router = new VueRouter({
  routes: [
    {
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]
})

To link to a named route, you can pass an object to the # to # attribute of # router link #:

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

This is similar to the code calling router Push () is one thing:

router.push({ name: 'user', params: { userId: 123 } })

Named view

Sometimes you want to display multiple views at the same time (at the same level) rather than nested display. For example, you can create a layout with two views, @ sidebar (side navigation) and @ main (main content). At this time, named views come in handy. You can have multiple individually named views in the interface instead of just one single exit. If "router view" has no name set, it defaults to "default".

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

A view is rendered with one component, so multiple views need multiple components for the same route. Make sure to use the {components} configuration correctly (with s):

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

Redirection and alias

redirect

Redirection is also completed through the configuration of "routes". The following example is redirection from / a "to / b:

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})

The target of redirection can also be a named route:

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: { name: 'foo' }}
  ]
})

Even a method that dynamically returns the redirection target:

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: to => {
      // Method receives the destination route as a parameter
      // return redirected string path / path object
    }}
  ]
})

alias

"Redirect" means that when a user visits / A, the URL will be replaced with / B, and then the matching route will be / b. what is the "alias"?

/The alias of a # is / B, which means that when the user accesses / b #, the URL will remain / B, but the route matching will be / A, just as the user accesses / a #.

The corresponding routing configuration above is:

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

The "alias" function allows you to freely map the UI structure to any URL, rather than being limited by the configured nested routing structure.

Routing component parameters

Using $route in a component will form a high coupling with its corresponding route, so that the component can only be used on some specific URL s, which limits its flexibility.

Decouple components and routes using # props #:

Replace coupling with $route +

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [{ path: '/user/:id', component: User }]
})

Decoupling by {props}

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

    // For routes containing named views, you must add the 'props' option for each named view separately:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})

This allows you to use the component anywhere, making it easier to reuse and test.

Boolean mode

If , props , is set to , true, route Params will be set as component properties.

Object mode

If props is an object, it will be set as is as a component property. Useful when props is static.

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

Object mode

If props is an object, it will be set as is as a component property. Useful when props is static.

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

Function mode

You can create a function that returns {props. In this way, you can convert parameters to another type, combine static values with routing based values, and so on.

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

Reference documents

Vue router official course: Install Vue Router

vue.js official website: Vue.js

Keywords: Front-end Vue.js

Added by rajivgonsalves on Fri, 04 Feb 2022 14:06:48 +0200