Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧭 What You’ll Learn
By the end of this chapter, you’ll be able to:
🚦 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:
🔧 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:
In the next chapter, we’ll create reusable components
like headers, footers, and cards to power your layout.
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.
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.
Answer:
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.
Answer:
Technically yes, but it’s not recommended. Vue Router provides essential SPA
features like URL mapping, history handling, navigation guards, and lazy
loading.
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.
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.
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.
Answer:
You can deploy your Vue SPA on:
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.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)