Vue router

How to use the Vue router, which is one of the basic components of the Vue application

Introduction

In a JavaScript web application, the router is the part that synchronizes the currently displayed view with the content of the browser's address bar.

In other words, this is the part of the URL that changes when you click on something in the page, and helps to show the correct view when you click on a specific URL.

Traditionally, the Web is built around URLs. When you click on a URL, a specific page will be displayed.

With the introduction of applications running in the browser and changing the appearance of users, many applications interrupt this interaction, so you must manually update the URL using the history API of the browser.

When you need to synchronize the URL to the view in the application, you need a router. This is a very common requirement, and all major modern frameworks now allow you to manage routing.

The Vue router library is an option for Vue.js applications. Vue does not force the use of this library. You can use any general routing library you need, or you can create your own History API integration, but the advantage of using Vue Router is that it canOfficial.

This means that it is maintained by the same person who maintains Vue, so you can get a more consistent integration in the framework and guarantee that it will always be compatible regardless of the future.

installation

Vue router can be obtained through the following waysnpmPackage namevue-router.

If you use Vue through the script tag, you can add a Vue router in the following ways:

<script src="https://unpkg.com/vue-router"></script>

unpkg.com is a very convenient tool, it can use every npm package in the browser through a simple link.

If you useVue CLI, Install using

npm install vue-router

Once installedvue-routerAnd use the script tag or make it available via Vue CLI, you can now import it into your application.

After you importvueAnd then you callVue.use(VueRouter)ToinstallationIt's in the app:

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

Vue.use(VueRouter)

After callingVue.use()By passing the router object, in any component of the application, you can access the following objects:

  • this.$routerIs a router object
  • this.$routeIs the current route object

Router object

Router object, usethis.$routerAfter installing the Vue router in the root Vue component, you can get any function from any component.

We can use the following methods to make the app navigate to the new route

  • this.$router.push()
  • this.$router.replace()
  • this.$router.go()

Similar topushState,replaceStatewithgoMethods of History API.

push()Used to go to a new route and add new items to the browser history.replace()The same, except that it will not push the new state to the history.

Usage sample:

this.$router.push('about') //named route, see later
this.$router.push({ path: 'about' })
this.$router.push({ path: 'post', query: { post_slug: 'hello-world' } }) //using query parameters (post?post_slug=hello-world)
this.$router.replace({ path: 'about' })

go()Move back and forth, accepting positive or negative numbers that can be returned in the history:

this.$router.go(-1) //go back 1 step
this.$router.go(1) //go forward 1 step

Define the route

I am usingVue single file componentIn this example.

In the template, I usenav tag that has 3 router-linkComponent, its label (home/login/about) and passtoAttributes.

Thisrouter-viewThe component is where the Vue router will place the content that matches the current URL.

<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link>
      <router-link to="/login">Login</router-link>
      <router-link to="/about">About</router-link>
    </nav>
    <router-view></router-view>
  </div>
</template>

A kindrouter-linkComponent renders aaThe label is the default setting (you can change it). Every time you change the route (by clicking a link or changing the URL),router-link-activeAdd the class to the element referencing the active path to style it.

In the JavaScript part we first include and install the router, then we define 3 Route composition.

We pass them torouterObject, and then pass this object to the Vue root instance.

This is the code:

<script>
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Home = { template: ‘<div>Home</div>’ }

const Login = { template: ‘<div>Login</div>’ }

const About = { template: ‘<div>About</div>’ }

const router = new VueRouter({ routes: [ { path: ‘/’, component: Home }, { path: ‘/login’, component: Login }, { path: ‘/about’, component: About } ] })

new Vue({ router }).$mount(’#app’) </script>

Generally, in a Vue application, you can use the following methods to instantiate and mount the root application:

new Vue({
  render: h => h(App)
}).$mount('#app')

When using a Vue router, you will not passrenderAttribute instead of usingrouter.

The syntax used in the above example:

new Vue({
  router
}).$mount('#app')

Shorthand for yes

new Vue({
  router: router
}).$mount('#app')

As seen in the example, we passed aroutesArray toVueRouterConstructor. There is one for each route in this arraypathwithcomponentparameter.

If you passnameThe parameters are the same, you have aNamed route.

Push and replace methods for passing parameters to routers using named routes

Remember how we used the Router object to push new state?

this.$router.push({ path: 'about' })

Using named routes, we can pass parameters to the new route:

this.$router.push({ name: 'post', params: { post_slug: 'hello-world' } })

The same reasonreplace():

this.$router.replace({ name: 'post', params: { post_slug: 'hello-world' } })

The application will present routing components that match the URL passed to the link.

Instantiate a new routing component that processes URLs and call its protective measures, and the old routing component will be destroyed.

Route guard

Since we mentionedguard, Let us introduce it.

You can think of them as lifecycle hooks or middleware, which are functions that are called at specific times during the execution of the application. You can join and change the execution of the route, redirect or cancel the request.

You can pass tobeforeEach()withafterEach()The attributes of the router.

  • beforeEach()Called before confirming navigation
  • beforeResolve()Called when beforeEach and all components are executedbeforeRouterEnterwithbeforeRouteUpdateThe guard was called, but before the navigation was confirmed. Final inspection (if required)
  • afterEach()Called after navigation is confirmed

What does "navigation confirmed" mean? We will see it in a second. At the same time, think of it as "the way applications can go."

The usage is:

this.$router.beforeEach((to, from, next) => {
  // ...
})
this.$router.afterEach((to, from) => {
  // ...
})

towithfromRepresents the object of our round-trip route.beforeEachThere is an additional parameternextIf we callfalseAs a parameter, it will prevent navigation and cause it to be unconfirmed. Just like in Node middleware, if you are familiar with it, you should always call next(), otherwise the execution will be stuck.

Single path components also have protective devices:

  • beforeRouteEnter(from, to, next)Called before confirming the current route
  • beforeRouteUpdate(from, to, next)Called when the routing changes but the components that manage it are still the same (use dynamic routing, see next)
  • beforeRouteLeave(from, to, next)Called when we left here

We mentioned navigation. To determine whether to confirm the navigation to the route, Vue Router performs some checks:

  • It callsbeforeRouteLeaveProtect current components
  • It calls the routerbeforeEach()Guard
  • It saysbeforeRouteUpdate()In any component that needs to be reused (if any)
  • It saysbeforeEnter()Protect the route object (I didn’t mention it, but you can take a lookHere)
  • It saysbeforeRouterEnter()In the component we should enter
  • It calls the routerbeforeResolve()Guard
  • If everything is ok, the navigation has been confirmed!
  • It calls the routerafterEach()Guard

You can use route-specific protection (beforeRouteEnterwithbeforeRouteUpdate(If it’s dynamic routing) as a lifecycle hook, then you can startData acquisition requestE.g.

Dynamic routing

The example above shows a different view based on the URL, which handles/,/loginwith/aboutroute.

A very common requirement is to handle dynamic routes, such as putting all posts in/post/, Each has an sl name:

  • /post/first
  • /post/another-post
  • /post/hello-world

You can use dynamic segmentation to achieve this.

These are static segments:

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/login', component: Login },
    { path: '/about', component: About }
  ]
})

We added a dynamic segment to handle blog posts:

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/post/:post_slug', component: Post },
    { path: '/login', component: Login },
    { path: '/about', component: About }
  ]
})

note:post_slugsyntax. This means you can use any string and map it topost_slugPlaceholder.

You are not limited to this syntax. Vue dependencyThis libraryAnalyze the dynamic route,Common expressions.

Now, within the "Release Route" component, we can use$route, And the post uses$route.params.post_slug:

const Post = {
  template: '<div>Post: {{ $route.params.post_slug }}</div>'
}

We can use this parameter to load content from the backend.

There can be any number of dynamic segments in the same URL:

/post/:author/:post_slug

Remember when we talked about what happens when a user navigates to a new route?

In the case of dynamic routes, what happens is slightly different.

Vue can reuse the current instance instead of destroying the current routing component and re-instantiating it, which is more efficient.

When this happens, Vue will callbeforeRouteUpdateLife cycle events. There, you can perform any operation you want:

const Post = {
  template: '<div>Post: {{ $route.params.post_slug }}</div>'
  beforeRouteUpdate(to, from, next) {
    console.log(`Updating slug from ${from} to ${to}`)
    next() //make sure you always call next()
  }
}

Use props

In the example, I used$route.params.*Access route data. Components should not be tightly coupled with the router. Instead, we can use props:

const Post = {
  props: ['post_slug'],
  template: '<div>Post: {{ post_slug }}</div>'
}

const router = new VueRouter({ routes: [ { path: ‘/post/:post_slug’, component: Post, props: true } ] })

noteprops: truePass to the route object to enable this feature.

Nested routes

Before I mentioned, you can have any number of dynamic segments in the same URL, for example:

/post/:author/:post_slug

Therefore, suppose we have an Author component responsible for the first dynamic segment:

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script> import Vue from ‘vue’ import VueRouter from ‘vue-router’

Vue.use(VueRouter)

const Author = { template: ‘<div>Author: {{ $route.params.author}}</div>’ }

const router = new VueRouter({ routes: [ { path: ‘/post/:author’, component: Author } ] })

new Vue({ router }).$mount(’#app’) </script>

We can insert the secondrouter-viewExamples of components in the Author template:

const Author  = {
  template: '<div>Author: {{ $route.params.author}}<router-view></router-view></div>'
}

We added the Post component:

const Post = {
  template: '<div>Post: {{ $route.params.post_slug }}</div>'
}

Then inject the internal dynamic routing into the VueRouter configuration:

const router = new VueRouter({
  routes: [{
    path: '/post/:author',
    component: Author,
    children: [
      path: ':post_slug',
      component: Post
    ]
  }]
})

Download mine for freeVue manual


More vue tutorials: