Vue JS Routing - Quick start guide

Ivan Radunovic

Feb 25, 20247 min read
Vue JS Routing - Quick start guide

Vue.js, a progressive JavaScript framework, is widely acclaimed for building user interfaces and single-page applications (SPAs). One of the core aspects of building SPAs is routing, which involves navigating between pages without the need for reloading the entire page.

This tutorial will guide you through Vue.js routing using Vue Router, covering installation, basic setup, advanced routing techniques, and FAQs.

Introduction to Vue Router

Vue Router is the official router for Vue.js. It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. With Vue Router, you can map components to routes and compose the application's interface using components, essentially allowing different parts of your application to be displayed based on the browser URL.

Getting Started

Installation

Before diving into routing, ensure you have Vue.js and Vue CLI installed. If you're starting a new project, create one using Vue CLI:

vue create my-vue-app

Navigate into your project directory and add Vue Router:

cd my-vue-app
vue add router

This command sets up Vue Router, updates your project with some boilerplate code, and creates a couple of views to get started.

Basic Routing

After installation, Vue Router allows you to map components to routes and configure how your application's interface changes as the user navigates through it. Here's a simple example of how to set up basic routing in a Vue.js application:

Define Your Routes

Create a file named router.js in your project's src directory, and define your routes:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
  ]
})

Configure Your Vue Instance

In your main entry file (usually main.js), import your router and tell Vue to use it:

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

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

Navigating with router-link

To navigate between pages, use the <router-link> component:

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

<router-view/> is where the matched components will be displayed.

Dynamic Route Matching

You might want to create a route to user profiles that includes their IDs. Vue Router allows you to have dynamic segments in the path that start with a colon:

routes: [
  // Dynamic segments start with a colon
  { path: '/user/:id', component: User }
]

Nested Routes

For applications with a complex structure, you might need nested routes. Vue Router allows you to nest routes within routes:

routes: [
  {
    path: '/user/:id',
    component: User,
    children: [
      {
        // UserProfile will be rendered inside User's <router-view>
        path: 'profile',
        component: UserProfile,
      },
    ],
  },
]

Advanced Routing Techniques

  • Programmatic Navigation: Navigate without <router-link>, using router.push, router.replace, or router.go.
  • Named Routes: Assign names to routes for easier reference.
  • Route Guards: Provide hooks for entering/exiting routes to control access or confirm navigation.
  • Lazy Loading: Load route components on demand to improve performance.

FAQs

Q: How do I pass props to a route component?

A: You can pass props to a route component by setting props: true in your route configuration and using dynamic segments in the path.

Q: Can I use Vue Router with a hash mode instead of history mode?

A: Yes, Vue Router supports hash mode. Simply set mode: 'hash' in your router configuration.

Q: How do I handle 404 pages?

A: Add a route with path: '*' and map it to a 404 component. This route should be last in your list of routes.

Q: Can I navigate between routes programmatically?

A: Yes, you can use this.$router.push('/path') within your Vue components to navigate programmatically.

Q: How do I secure my routes?

A: Use route guards like beforeEnter or global guards such as beforeEach to implement authentication and authorization.

Conclusion

This tutorial has guided you through the fundamentals of Vue Router, from basic setup and navigation to more advanced features like dynamic routing, nested routes, and route guards.

By understanding these concepts, you can create more interactive and user-friendly web applications. Remember, Vue Router's flexibility and integration with Vue.js core make it a powerful tool for your development projects.

Keep experimenting with different routing strategies and configurations to enhance your Vue.js applications further.

Happy coding!

Share
Author Photo
Ivan Radunovic is a Senior Developer with over 11 years of experience in web development. His expertise are Laravel SaaS solutions. So far he developed or took part in 300+ Laravel projects.

More Vue.js tutorials

Hosting Vue on Cloudflare Pages

Hosting Vue application on Cloudflare is very simple process. It's free and includes a CDN, caching and SSL.

Feb 22, 2024 Ivan Radunovic