Introduction to the

Most web sites or applications have multiple static or dynamically generated HTML pages. For more traditional web sites, there is a document Object Model (DOM) with one page per URL route. However, for _ single-page applications, each “page” or view is rendered in an HTML page. User interface (UI) frameworks like vue.js render these pages and components when needed using the virtual DOM. The _ virtual DOM_ is a JavaScript representation of the original DOM that is easier for clients to update.

When a user accesses a one-page application, the application compares itself to the virtual DOM and only re-renders the changed portions of the web page. This prevents the page from flashing white when a link is clicked. Suppose you have three sections on a web page: header, content, and footer. When you navigate to another URL, Vue will only render the content area of the application that changes between pages.

In vue.js, you can create several views using the first-party library Vue Router. This router associates a view with a URL. In this tutorial, you will learn how to add the Vue Router library, integrate it into your project, and create dynamically generated routes. You’ll also learn about the different types of routing you can use as a developer. When you’re done, you’ll have an application that can navigate using a variety of methods.

To illustrate these concepts, you will create a small application that displays airport information. When the user clicks on an airport card, the program navigates to a dynamic view of the details of that airport. To do this, the program reads a URL parameter and filters out the data based on that parameter.

The premise condition

To complete this tutorial, you will need.

  • Install the Node.js version on your computer10.6.0Or higher. To install on macOS or Ubuntu 18.04, follow theHow toOn macOSInstall Node.js and create a local development environment”, or followHow to Install Node.js on Ubuntu 18.04″The use of PPAInstall”Partial installation.
  • It’s on your machineInstall the Vue CLIAnd generate a new project. In this tutorial, do not select the Vue Router when creating the application. You will install it manually in the first step of this tutorial. The project name will beairport-codes, which will serve as the root directory.
  • You also need a basic knowledge of JavaScript, HTML, and CSS, which you can find in our “How to Build A Website with HTML” series, “How to Build a Website with CSS” series, and “How to Code with JavaScript” series.

Step 1 – Set up the sample application

The application you want to build to learn Vue Router will need some initial data. In this step, you will create and structure the data so that it can be accessed by your Vue application later in the tutorial.

To add this data set, you need to create a data directory and create a JavaScript file called ports.js. If you are not in the SRC directory, CD goes to it first.

cd src
Copy the code

Then make a data directory.

mkdir data
Copy the code

Now create a data/ ports.js file and open it in your text editor.

Add the following to create data for your application.

airport-codes/src/data/airports.js

export default[{name: 'Cincinnati/Northern Kentucky International Airport'.abbreviation: 'CVG'.city: 'Hebron'.state: 'KY'.destinations: {
      passenger: [ 'Toronto'.'Seattle/Tacoma'.'Austin'.'Charleston'.'Denver'.'Fort Lauderdale'.'Jacksonville'.'Las Vegas'.'Los Angeles'.'Baltimore'.'Chicago'.'Detroit'.'Dallas'.'Tampa'].cargo: [ 'Anchorage'.'Baltimore'.' Chicago' , 'Indianapolis'.'Phoenix'.'San Francisco'.'Seattle'.'Louisville'.'Memphis']}}, {name: 'Seattle-Tacoma International Airport'.abbreviation: 'SEA'.city: 'Seattle'.state: 'WA'.destinations: {
      passenger: [ 'Dublin'.'Mexico City'.'Vancouver'.'Albuquerque'.'Atlanta'.'Frankfurt'.'Amsterdam'.'Salt Lake City'.'Tokyo'.'Honolulu'].cargo: [ 'Spokane'.'Chicago'.'Dallas'.' Shanghai'.'Cincinnati'.'Luxenbourg'.'Anchorage'.'Juneau'.'Calgary'.'Ontario']}}, {name: 'Minneapolis-Saint Paul International Airport'.abbreviation: 'MSP'.city: 'Bloomington'.state: 'MN'.destinations: {
      passenger: [ 'Dublin'.'Paris'.'Punta Cana'.'Winnipeg'.'Tokyo'.'Denver'.'Tulsa'.'Washington DC'.'Orlando'.'Mexico City'].cargo: [ 'Cincinnati'.'Omaha'.'Winnipeg'.'Chicago'.'St. Louis'.'Portland'.'Philadelphia'.'Milwaukee'.'Ontario']}}]Copy the code

This data is an array of objects composed of several airports in the United States. In this application, you’re going to iterate over this data, generating cards with name,abbreviation, City, and State properties. When a user clicks on a card, you will use the Vue Router to send them to a dynamic view and read from these properties. From there, you will create a nested routine to display the information stored in the Destination property.

Save and exit the file.

Next, create a home.vue component in a directory called Views. You can create this directory and component by opening your terminal and using mkdir and touch commands.

Run the following command to create the directory.

mkdir views
Copy the code

Then create the home.vue file.

touch views/Home.vue
Copy the code

The home.vue component will act as the Home page for the application. In it, you’ll use the V-for directive to traverse the airports. Js data set and display each airport in a card.

Add the following code to home.vue.

airport-codes/src/views/Home.vue

<template>
  <div class="wrapper">
    <div v-for="airport in airports" :key="airport.abbreviation" class="airport">
      <p>{{ airport.abbreviation }}</p>
      <p>{{ airport.name }}</p>
      <p>{{ airport.city }}, {{ airport.state }}</p>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import allAirports from '@/data/airports.js'

export default {
  setup() {
    const airports = ref(allAirports)
        return { airports }
    }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-column-gap: 1rem;
  max-width: 960px;
  margin: 0 auto;
}
.airport {
  border: 3px solid;
  border-radius:.5rem;
  padding: 1rem;
}
.airport p:first-child {
  font-weight: bold;
  font-size: 2.5 rem;
  margin: 1rem 0;
}
.airport p:last-child {
  font-style: italic;
  font-size:.8rem;
}
</style>
Copy the code

You may notice that some CSS is included in this snippet. In the home.vue component, you are walking through a collection of airports, each of which has been assigned a CSS class: Airport. This CSS adds styles to the generated HTML, making each airport look like a card by making a border. :first-child and: last-Child are _ pseudo-_ selectors that apply different styles to the first and last P tags in HTML, where div has the category airport.

Save and close the file.

Now that you have created the initial view and local data set, you will install the Vue Router in the next step.

Step 2 – Install the Vue Router

You can install the Vue Router in several ways. If you are creating a new project from scratch using the Vue CLI, you can select the Vue Router in the prompt; The Vue CLI will then install and configure it for you. However, for the purposes of this tutorial, we will assume that you did not select the Vue Router option in your CLI Settings. You will install the Vue Router through NPM.

To install the Vue Router, first move from the SRC directory back to your project root directory.

cd.Copy the code

Then run the following program in a terminal window at the root of your project.

npm i vue-router@next
Copy the code

You may have noticed @next in this command. Since this project uses Vue 3 and the Composition API, you are telling NPM to download the latest experimental version of the library. If you want to learn more about the current version, check out the Vue Router release page on GitHub.

This will download the Vue-Router library from NPM and add it to your package.json file so that it will be downloaded automatically the next time you run NPM Install.

The next step is to create your routing file. This file will contain all possible routes that the user can browse. When a route is accessed in the URL bar, components associated with the URL route are mounted.

On your terminal, in the SRC directory, move to the SRC directory and create a Router directory.

cd src
mkdir router
Copy the code

Next, create an index.js file in the Router directory.

touch router/index.js
Copy the code

Open the file you just created in the editor of your choice. The first thing to do is import the Vue Router library. In fact, you don’t need to access everything in this library to create a route. You can choose to cancel the structure or import only what you need to minimize the size of the package. In this case, you need two functions from vue-Router: createWebHistory and createRouter. Each of these functions creates a history that the user can trace and builds a router object for the Vue.

Add the following code to router/index.js.

airport-codes/src/router/index.js

import { createWebHistory, createRouter } from "vue-router"
Copy the code

Next, add the following highlighted lines to create and export your router.

airport-code/src/router/index.js

import { createWebHistory, createRouter } from "vue-router"

const router = createRouter({
  history: createWebHistory(),
})

export default router
Copy the code

This file exports a router object that is returned from the createRouter function. The object you pass in has two attributes: history and routes. The history property contains the history generated from createWebHistory, and Routes is an array of objects. You will add routes later in this tutorial.

Next, import the Home view and create an array of objects, storing them in a const named Routes.

airport-codes/src/router/index.js

import { createWebHistory, createRouter } from "vue-router"
import Home from "@/views/Home.vue"

const routes = [
  {
    path: "/".name: "Home".component: Home,
  },
]

const router = createRouter({ ... })

export default router
Copy the code

Each route is an object with three attributes.

  • path: URL address
  • name: a name to use to reference a route in your project
  • component: When entered in the URL bar of the browserpath, the components will be installed.

Now that your Routes array has been created, you will need to add it to the exported Router object.

Add routes after the key/value pair for history. This is JavaScript shorthand for routes: routes.

airport-codes/src/router/index.js

import { createWebHistory, createRouter } from "vue-router"

const routes = [ ... ]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
Copy the code

At this point, the Vue Router is already integrated into your project, and you have registered a route. Save and exit the file.

From another terminal, run the following command to start a development server on your local machine.

npm run serve
Copy the code

If you access localhost:8080/ in a browser window, you won’t see the home.vue component yet. The final step in the integration process is to tell Vue to listen for the router/index.js file and inject the installed components where
is referenced. To do this, you need to reference it in your application’s SRC /main.js file.

First, open SRC /main.js. Then add the highlighted row below.

airport-codes/src/main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')
Copy the code

With this link to createApp’s.use() function, vue.js is now listening for route changes and taking advantage of your SRC /router/index.js file. However, the Vue Router has no way to display the installed home.vue components. To do this, you need to add the router-View component to your app. vue file. This component tells the Vue Router to mount any components associated with the route where
resides.

Save and exit the main.js file.

Next, open the app.vue file. Delete the default content and replace it with the following.

airport-codes/src/App.vue

<template>
  <router-view />
</template>
Copy the code

Save and exit the file.

Now go to localhost:8080/ in your browser. You’ll notice that the home.vue component is rendered, as shown in the screenshot below.

The Vue Router has now been downloaded and integrated with the registered route. In the next section, you will create additional routes, including two internal pages and a default 404 page, if no route is detected.

Step 3 – Create an internal page

At this point, your app.vue can render any component configured in your SRC /router/index.js file. When using Vue CLI-generated projects, one of the directories created for you is Views. This directory contains any.vue components that map directly to routes in the router/index.js file. It’s important to note that this is not automated. You will need to create a.vue and import it into your router file to register, as detailed earlier.

Before you define all the other routes, you can create a default route. In this tutorial, this default route will be used as a 404-Not Found page — a fallback if no route is Found.

First, create the view that will be the 404 page. Change to the Views directory.

cd views
Copy the code

Then create a file called PageNotFound. Vue.

touch PageNotFound.vue
Copy the code

In your text editor, open the PageNotFound. Vue file that you just created. Add the following HTML code to give the view something to render.

airport-codes/src/views/PageNotFound.vue

<template>
  <div>
    <h1>404 - Page Not Found</h1>
    <p>This page no longer exists or was moved to another location.</p>
  </div>
</template>
Copy the code

Save and close the file.

Now that the PageNotFound. Vue component has been created, it’s time to create a comprehensive route for your application. Open the SRC /router/index.js file in your text editor and add the following highlighting code.

airport-codes/src/router/index.js

import { createWebHistory, createRouter } from "vue-router"
import Home from "@/views/Home.vue"
import PageNotFound from '@/views/PageNotFound.vue'

const routes = [
  {
    path: "/".name: "Home".component: Home,
  },
  {
    path: '/:catchAll(.*)*'.name: "PageNotFound".component: PageNotFound,
  },
]
...
Copy the code

Vue Router for Vue 3 uses a custom RegEx. The value of Path contains this new RegEx, which tells Vue to render PageNotFound. Vue for each route unless the route has already been defined. The catchAll in this route refers to a dynamic segment in the Vue Router, and (.*) is a regular expression that can capture any string.

Save this file and access your application in a browser window: localhost:8080/not-found. You will find the PageNotFound. Vue component rendered in your browser, as shown below.

You’re free to change this URL to anything else; You’ll get the same result.

Before moving on, create another route for your application. This route will be an about page.

Open the terminal of your choice and create a file in the views directory.

touch About.vue
Copy the code

In your text editor, open the about. vue file you just created. Add the following HTML to create more information about your site.

airport-codes/src/views/About.vue

<template>
  <div>
    <h1>About</h1>
    <p>This is an about page used to illustrate mapping a view to a router with Vue Router.</p>
  </div>
</template>
Copy the code

Save and close the file.

After creating the view, open the SRC /router/index.js file in a text editor, import the about. vue component, and register a new path as/About.

airport-codes/src/router/index.js

import { createWebHistory, createRouter } from "vue-router"
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'
import PageNotFound from '@/views/PageNotFound.vue'.const routes = [
  {
    path: "/".name: "Home".component: Home,
  },
  {
    path: '/about'.name: "About".component: About,
  },
  {
    path: '/:catchAll(.*)*'.name: "PageNotFound".component: PageNotFound,
  },
]
...
Copy the code

Save and close the file.

At this point, you have three different routes.

  • localhost:8080/, its path isHome.vue
  • localhost:8080/aboutAnd its path isAbout.vue
  • Any other route, by default, it points toPageNotFound.vue

Once you have saved this file, open your browser and first go to localhost:8080/. Once the app loads, you’ll find the contents of home.vue: a collection of airport cards.

Continue testing these routes by visiting localhost:8080/about. This is a static route, so you’ll find the contents of the about. vue component, which in this case contains a heading and a paragraph.

Next, you can test the PageNotFound. Vue component by accessing anything else in your browser. For example, if you access localhost:8080/some-other-route, the Vue Router will default to the catchAll route because the route is not defined.

As this step illustrates, the Vue Router is a convenient first-party library that can render a component associated with a particular route. In this step, the library is downloaded and globally integrated through the main.js file and configured in your SRC /router/index.js file.

So far, most of your routes are _ exact _ routes. This means that the component will only be mounted if the URL fragment exactly matches the router’s path. However, there are other types of routes that have their own purpose and can dynamically generate content. In the next step, you will implement different types of routing and learn when to use one of them.

Step 4 – Create a route with parameters

At this point, you have created two exact routes and a dynamic route to the 404 page. However, there are more types of routes for Vue Routers. You can use the following routes in the Vue Router.

  • Dynamic routing. A route with dynamic parameters that your application can reference to load unique data.
  • Name the route. You can usenameAttribute access route. All routes created at this time have onenameProperties.
  • Nested routines by. The route associated with the subroutine.
  • Static or precise routing. A staticpathValue of the route.

In this section, you will create a dynamic route that displays individual airport information and a nested routine for airport destinations.

Dynamic route

Dynamic routing is useful when you want to reuse a view to display different data based on routing. For example, if you want to create a view that displays airport information based on the airport code in the URL bar, you can use a dynamic route. In this case, if you visit route is localhost: 8080 / airport/SVG, your application will show the code to the CVG airport data, namely the Cincinnati/northern Kentucky international airport. Next, you will create the view as described.

Open your terminal and create a new.vue file with the touch command. If SRC were your current working directory, the command would look like this.

touch views/AirportDetail.vue
Copy the code

Once created, open the file in a text editor of your choice. Go ahead and create your template and script tags to set up this component.

airport-codes/src/views/AirportDetail.vue

<template>
  <div>

  </div>
</template>

<script>
export default {
  setup(){}}</script>
Copy the code

Save and close the file.

Next, you need to register the view in the SRC /router/index.js file. Open the file in your text editor and add the following highlighted lines.

airport-codes/src/router/index.js

import Home from '@/views/Home.vue'
import About from '@/views/About.vue'
import AirportDetail from '@/views/AirportDetail.vue'
import PageNotFound from '@/views/PageNotFound.vue'.const routes = [
  {
    path: "/".name: "Home".component: Home,
  },
  {
    path: '/about'.name: "About".component: About,
  },
  {
    path: '/airport/:code'.name: "AirportDetail".component: AirportDetail,
  },
  {
   path: '/:catchAll(.*)*'.name: "PageNotFound".component: PageNotFound,
  },
]
...
Copy the code

The code in this new route is called the _ argument _. A parameter is any value that can be accessed by that name in your application. In this case, you have a parameter called code. Next, you will display the information associated with the abbreviation by using this parameter.

Save and close the file.

Now that you have some data, open the airportDetail.vue component again. Import airport data in this component.

airport-codes/src/views/AirportDetail.vue

.<script>
import airports from '@/data/airports.js'

export default {
  setup(){}}</script>
Copy the code

Next, create a calculated property that returns an object from the array if the object’s Dec. property matches the :code parameter in the URL. In Vue 3, you need to remove structured computed from the Vue library.

airport-codes/src/views/AirportDetail.vue

.<script>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import airports from '@/data/airports.js'

export default {
  setup() {
  const route = useRoute()
    const airport = computed(() = > {
        return airports.filter(a= > a.abbreviation === route.params.code.toUpperCase())[0]})return { airport }
  }
}
</script>
Copy the code

The evaluated property uses the JavaScript filter array method, which returns an array of objects if the criteria are met. Since you only want one object, the code will always return the first object, which it will access using the [0] index syntax. Route.params. code is how you access parameters defined in your router file. To access the attributes of the route, you need to import a function called useRoute from vue-Router. Now when you access a route, you can access all the attributes of the route immediately. You are using dot notation to access the code parameter and retrieve its value.

At this point, the calculated property will return a single airport object if the code in the URL matches the abbreviation property. This means that you have access to all object properties of an airport and can build a template for that component.

Go ahead and edit the airportDetail. vue file in your text editor to build your template to display the airport information.

airport-codes/src/views/AirportDetail.vue

<template>
 <div>
   <p>{{ airport.name }} ({{ airport.abbreviation }})</p>
   <p>Located in {{ airport.city }}, {{ airport.state }}</p>
 </div>
</template>.Copy the code

Open your browser, access localhost: 8080 / airport/sea. Information about Seattle-Tacoma International Airport will appear in your browser, as shown below.

Nested routes

As your application grows, you may find that you have many routes associated with the parent. A good example of this is a series of user-specific routes. If you have a user named foo, you can create multiple nested routes for the same user, each starting with /user/foo/. When the user is on the /user/foo/profile path, the user views the profile page associated with them. A user’s posts page might have a route to /user/foo/posts. This nesting gives you the ability to organize your routes and your components. For more information on this, see the Vue Router documentation.

You can apply this pattern to the applications you build in this tutorial. In this section, you will add a view to show the destinations supported by each airport.

Open your terminal, in the SRC directory, and create a new file called AirportDestinations. Vue.

touch views/AirportDestinations.vue
Copy the code

Next, open your text editor and add the following.

airport-codes/src/views/AirportDestinations.vue

<template>
  <h1>Destinations for {{ airport.name }} ({{ airport.abbreviation }}</h1>
  <h2>Passenger</h2>
  <ul>
    <li v-for="(destination, i) in airport.destinations.passenger" :key="i">
      {{ destination }}
    </li>
  </ul>
  <h2>Cargo</h2>
  <ul>
    <li v-for="(destination, i) in airport.destinations.cargo" :key="i">
      {{ destination }}
    </li>
  </ul>
</template>

<script>
  import { computed } from 'vue'
  import { useRoute } from 'vue-router'
  import airports from '@/data/airports.js'

  export default {
    setup() {
      const route = useRoute()
      const airport = computed(() = > {
        return airports.filter(a= > a.abbreviation === route.params.code.toUpperCase())[0]})return { airport }
  }
}
</script>
Copy the code

This view renders all the destinations for each airport in the ports.js file. In this view, you are using the V-for command to traverse the destination. As with the AirportDetail.vue view, you are creating a calculated property called airport to get the airport that matches the :code parameter in the URL bar.

Save and close the file.

To create a nested route, you need to add the children attribute to your route object in the SRC /router/index.js file. The child (nested) routing object contains the same attributes as its parent object.

Open router/index.js and add the following highlighted lines.

airport-codes/src/router/index.js

import Home from '@/views/Home.vue'
import About from '@/views/About.vue'
import AirportDetail from '@/views/AirportDetail.vue'
import AirportDestinations from '@/views/AirportDestinations.vue'
import PageNotFound from '@/views/PageNotFound.vue'.const routes = [
    ...
  {
    path: '/airport/:code'.name: "AirportDetail".component: AirportDetail,
        children: [{path: 'destinations'.name: 'AirportDestinations'.component: AirportDestinations } ] }, ... ] .Copy the code

The path of this child route is short compared to its parent route. This is because, for nested routes, you don’t need to add the entire route. A child route inherits the path of its parent route and presets it to the path of the child route.

Open your browser window and access localhost: 8080 / airport/MSP/destinations. There doesn’t seem to be anything different from the parent airportDetails.vue. This is because when using nested routines, you need to include a
component in the parent route. When accessing a child path, Vue injects the contents of the child view into the parent view.

airport-codes/src/views/AirportDetail.vue

<template>
 <div>
   <p>{{ airport.name }} ({{ airport.abbreviation }})</p>
   <p>Located in {{ airport.city }}, {{ airport.state }}</p>
     <router-view />
 </div>
</template>
Copy the code

In this case, AirportDestinations. Vue, when accessed ina browser, will display an unordered list of passenger and cargo flight destinations supported by Minneapolis-St. Paul International Airport.

In this step, you created dynamic and nested routes and learned how to use computed properties to check the :code parameter in the URL bar. Now that all routes have been created, in the final step you will navigate between different types of routes by creating links using the
component.

Step 5 – Navigate between routes

There are a few considerations that you should be aware of when dealing with single-page applications. Since each page is guided to a single HTML page, using the standard anchor () to navigate between internal routes will not work. Instead, you’ll need to use the
component that the Vue Router provides.

Unlike standard anchor tags, router-Link provides many different ways to link to other routes in your application, including using named routes. A named route is one that has a name attribute associated with it. Each link you have created so far has a name that is already associated with it. Later in this step, you will learn how to use name instead of path to navigate.

use<router-link />component

When you initially integrate the Vue Router into your application, the
component is imported globally. To use this component, you will add it to your template and give it an item value.

Open the home.vue component in the Views directory in your editor. This view shows you each airport in the ports.js file. You can replace the included div tags with router-link so that each card can be clicked into its own detailed view.

Add the following highlighted line to home.vue.

airport-codes/src/views/Home.vue

<template>
    <div class="wrapper">
        <router-link v-for="airport in airports" :key="airport.abbreviation" class="airport">
            <p>{{ airport.abbreviation }}</p>
            <p>{{ airport.name }}</p>
            <p>{{ airport.city }}, {{ airport.state }}</p>
        </router-link>
    </div>
</template>.Copy the code

At a minimum, router-Link requires an item called to. The to item accepts an object with several key/value pairs. Since this card uses the V-for instruction, these cards are data-driven. You need to be able to navigate to the AirportDetail.vue component. If you look at the path of the component, it goes through /airports/:code.

When navigated through the Path property, it is a one-to-one match. Add the highlighted fragment below.

airport-codes/src/views/Home.vue

<template>
    <div class="wrapper">
        <router-link :to="{ path: `/airports/${airport.abbreviation}` }" v-for="airport in airports" :key="airport.abbreviation" class="airport">.</router-link>
    </div>
</template>.Copy the code

In this code, you are using JavaScript string interpolation to dynamically insert the airport code as the value of the PATH property. However, as your application grows in size, you may find that navigating to different routes through Path is not the best approach. In fact, it is generally considered best to use named routes for navigation.

To implement a named route, use the name of the route, not the path. If you refer to SRC /router/index.js, you’ll find airportdetail.vue, which is called AirportDetail.

airport-codes/src/views/Home.vue

<template>
    <div class="wrapper">
        <router-link :to="{ name: 'AirportDetail' }" v-for="airport in airports" :key="airport.abbreviation" class="airport">.</router-link>
    </div>
</template>.Copy the code

The advantage of using named routes over exact routes is that named routes do not depend on the path of the route. The URL structure always changes during development, but the name of the route rarely does.

You may notice that you cannot pass in the airport code as you did earlier with exact routing. If you need to pass in parameters in a named route, you will need to add the params attribute, which contains an object representing your parameters.

airport-codes/src/views/Home.vue

<template>
    <div class="wrapper">
        <router-link :to="{ name: 'AirportDetail', params: { code: airport.abbreviation } }" v-for="airport in airports" :key="airport.abbreviation" class="airport">.</router-link>
    </div>
</template>.Copy the code

Save the file and view it in your browser at localhost:8080. Click the Seattle – tacoma airport card, now will you navigate to the localhost: 8080 / airport/sea.

Programmed navigation

The
component is useful when you need to navigate to another view in your HTML template. But what about when you need to navigate between routes in a JavaScript function? The Vue Router provides a solution to this problem called _ programmatic navigation _.

Earlier in this tutorial, you created an umbrella route called PageNotFound. If the airport compute property returns undefined in the AirportDetail.vue and AirportDestinations. Vue components, it will be a good user experience to always navigate to that page. In this section, you will implement this functionality.

In your text editor, open the AirportDetail.vue component. To do this, check whether airport.value is undefined. This function will be called when the component is first installed, which means you will need to use Vue’s lifecycle methods.

Add the highlighted row below.

airport-codes/src/views/AirportDetail.vue

<template>
  <div v-if="airport">
   <p>{{ airport.name }} ({{ airport.abbreviation }})</p>
   <p>Located in {{ airport.city }}, {{ airport.state }}</p>
   <router-view />
  </div>
</template>

<script>
    import { computed, onMounted } from 'vue'
    import { useRoute } from 'vue-router'
    import airports from '@/data/airports.js'
    import router from '@/router'

    export default {
            setup() {
        const route = useRoute()
                const airport = computed(() = > {
                    return airports.filter(a= > a.abbreviation === route.params.code.toUpperCase())[0]
                })

                onMounted(() = > {
                    if(! airport.value) {// Navigate to 404 page here}})return { airport }
            }
    }
</script>
Copy the code

In this onMounted function, you check whether airport.value is a false value. If so, then you route to PageNotFound. You can handle programmatic routing in the same way you handle router-link components. Since you can’t use a component in a JavaScript function, you need to use router.push({… }). The push method of the Router object accepts the value of the to item when using the link component.

/src/views/AirportDetail.vue

<script>. onMounted(() = > {
        if(! airport.value) { router.push({name: 'PageNotFound'})}})...</script>
Copy the code

If the route does not exist, or the data does not return properly, this will protect the user from damaging the page.

Save the file and navigate to the localhost: 8080 / airport/ms. Since MS is not the airport code in the data, the airport object will be undefined and the router will redirect you to the 404 page.

conclusion

In this tutorial, you used the Vue Router to create a Web application that routes between views. You learned about different types of routing, including precise, named, and nested, as well as creating links with parameters using the router-link component. In the last step, you provide programmatic navigation in JavaScript by taking advantage of the router’s push() function.

For more information on the Vue Router, it is recommended to read through its documentation. The CLI tools in particular have many additional features that are not covered in this tutorial. For more tutorials on Vue, see the Vue topics page.