Creating Single Page Applications (SPAs) with Vue.js — A Complete Beginner’s Guide

1.59K 0 0 0 0

📘 Chapter 3: Creating Views and Routing with Vue Router

🧭 What You’ll Learn

By the end of this chapter, you’ll be able to:

  • Install and configure Vue Router
  • Define routes and associate them with components
  • Navigate using router links
  • Create dynamic and nested routes
  • Use route parameters and query strings
  • Apply navigation guards
  • Implement scroll behavior and active link styling

🚦 What Is Vue Router?

Vue Router is the official routing library for Vue.js. It allows you to build Single Page Applications (SPAs) that can navigate between views without full-page reloads, using the History API or hash mode.

Vue Router manages:

  • The navigation logic
  • The URL-to-view mapping
  • Route transitions and guards
  • Dynamic route matching

🔧 Step 1: Install Vue Router

In a Vite project:

bash

 

npm install vue-router@4

In a Vue CLI project:

bash

 

vue add router

Or manually:

bash

 

npm install vue-router


📂 Project File Structure With Vue Router

bash

 

src/

── main.js

── App.vue

── router/

│   └── index.js

── views/

│   ── Home.vue

│   ── About.vue

│   └── Contact.vue

└── components/


🛠️ Step 2: Set Up Vue Router in Your Project

router/index.js:

js

 

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

import Home from '../views/Home.vue'

import About from '../views/About.vue'

 

const routes = [

  { path: '/', name: 'Home', component: Home },

  { path: '/about', name: 'About', component: About }

]

 

const router = createRouter({

  history: createWebHistory(),

  routes,

})

 

export default router

main.js:

js

 

import { createApp } from 'vue'

import App from './App.vue'

import router from './router'

 

createApp(App).use(router).mount('#app')


🧩 Step 3: Create View Components

Each route corresponds to a Vue component inside /views.

Example: views/Home.vue

vue

 

<template>

  <div>

    <h1>Home Page</h1>

    <p>Welcome to our Vue SPA!</p>

  </div>

</template>

views/About.vue

vue

 

<template>

  <div>

    <h1>About Page</h1>

    <p>This is the about section of the site.</p>

  </div>

</template>


🔗 Step 4: Navigate With <router-link>

Use router-link instead of a href to navigate without page reloads.

vue

 

<template>

  <nav>

    <router-link to="/">Home</router-link>

    <router-link to="/about">About</router-link>

  </nav>

</template>

Add Styling for Active Links:

css

 

.router-link-active {

  font-weight: bold;

  color: #42b983;

}


📄 Step 5: Add <router-view> to App.vue

This is where your routed components will be displayed.

vue

 

<template>

  <div id="app">

    <Navbar />

    <router-view />

  </div>

</template>


🔁 Step 6: Dynamic Routes and Params

You can define routes with parameters using :param.

index.js:

js

 

{ path: '/user/:id', name: 'UserProfile', component: User }

Accessing params in User.vue:

vue

 

<script>

import { useRoute } from 'vue-router'

 

export default {

  setup() {

    const route = useRoute()

    return { id: route.params.id }

  }

}

</script>

URL Example: /user/42 → route.params.id === '42'


🧭 Step 7: Programmatic Navigation

Use JavaScript to navigate between routes:

js

 

import { useRouter } from 'vue-router'

 

const router = useRouter()

router.push('/about')

router.push({ name: 'UserProfile', params: { id: 10 } })


🔍 Step 8: Query Strings

Routes can include query strings:

js

 

router.push({ path: '/search', query: { q: 'vue' } })

URL Result: /search?q=vue

Access it with:

js

 

const route = useRoute()

const searchTerm = route.query.q


🧬 Step 9: Nested Routes

Nested routes allow child components inside parents.

js

 

const routes = [

  {

    path: '/dashboard',

    component: DashboardLayout,

    children: [

      { path: '', component: DashboardHome },

      { path: 'settings', component: Settings },

    ]

  }

]

Inside the layout component:

vue

 

<router-view /> <!-- renders DashboardHome or Settings -->


🔒 Step 10: Navigation Guards

Navigation guards protect routes or control flow.

Global Guard:

js

 

router.beforeEach((to, from, next) => {

  const isAuthenticated = false

  if (to.name !== 'Home' && !isAuthenticated) next({ name: 'Home' })

  else next()

})

Per-Route Guard:

js

 

{

  path: '/dashboard',

  component: Dashboard,

  beforeEnter: (to, from, next) => {

    if (auth.isLoggedIn()) next()

    else next('/login')

  }

}


🌀 Scroll Behavior

Ensure users start at the top of the page on navigation:

js

 

const router = createRouter({

  history: createWebHistory(),

  routes,

  scrollBehavior(to, from, savedPosition) {

    return savedPosition || { top: 0 }

  }

})


📊 Route Configuration Table

Option

Description

path

URL path of the route

name

Named identifier for programmatic routing

component

Vue component to render

children

Nested route definitions

redirect

Auto-redirect to another route

meta

Custom data (e.g., auth)


Routing Features Recap

Feature

Benefit

router-link

Declarative, seamless navigation

router-view

Displays the current component

Dynamic routes

Use URL parameters to customize content

Nested routes

Layouts and subviews

Navigation guards

Protect routes with logic

Scroll behavior

Improved UX during navigation


Summary

Vue Router makes building SPAs easy, modular, and powerful.

You’ve now learned how to:

  • Set up and use Vue Router
  • Create pages/views and link them
  • Handle dynamic and nested routes
  • Use programmatic navigation
  • Protect routes and manage scroll position


In the next chapter, we’ll create reusable components like headers, footers, and cards to power your layout.

Back

FAQs


❓1. What is a Single Page Application (SPA)?

Answer:
A Single Page Application is a web app that loads a single HTML file and dynamically updates the content without refreshing the page. This allows for a smoother user experience, similar to desktop or mobile apps.

❓2. Why should I use Vue.js to build an SPA?

Answer:
Vue.js is lightweight, beginner-friendly, and has a powerful ecosystem. It supports component-based architecture and works seamlessly with Vue Router for SPA navigation. It’s a great choice for fast, reactive, and scalable SPAs.

❓3. What are the essential tools needed to build a Vue.js SPA?

Answer:

  • Vue CLI or Vite (project scaffolding)
  • Vue Router (for client-side navigation)
  • Pinia or Vuex (for state management)
  • Single File Components (.vue)
  • Axios or Fetch API (for server communication, if needed)

❓4. How does routing work in a Vue.js SPA?

Answer:
Vue Router handles navigation in the browser without reloading pages. It maps URL paths to Vue components and updates the view dynamically using the browser’s History API.

❓5. Can I use Vue.js without Vue Router for an SPA?

Answer:
Technically yes, but it’s not recommended. Vue Router provides essential SPA features like URL mapping, history handling, navigation guards, and lazy loading.

❓6. What is the difference between Vuex and Pinia?

Answer:
Both are state management libraries. Vuex is the older, more complex option, while Pinia is the official replacement for Vue 3—lighter, easier to use, and modular.

❓7. Can I build an SPA with Vue using only CDN links?

Answer:
Yes, but it's only suitable for small-scale SPAs. For larger projects, using the Vue CLI or Vite offers better file organization, hot reloading, and tooling support.

❓8. How do I handle SEO with a Vue SPA?

Answer:
SPAs typically have poor SEO out of the box because content is rendered via JavaScript. Use pre-rendering (e.g., with Prerender.io) or switch to Server-Side Rendering (SSR) with Nuxt.js for better SEO.

❓9. What hosting options are available for deploying Vue SPAs?

Answer:
You can deploy your Vue SPA on:

  • Netlify (easy integration with Git)
  • Vercel
  • Firebase Hosting
  • GitHub Pages
  • Render or DigitalOcean App Platform

❓10. Is Vue.js suitable for large-scale Single Page Applications?

Answer:
Yes. Vue.js is modular and scalable. With features like lazy loading, component splitting, Pinia/Vuex for state management, and Vue Router, it can power large, production-ready SPAs effectively.