Vue 3·Vue from reactivity to a routed app

Routing

Add client-side routes, route params and navigation guards.

Intermediate 13 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • Install vue-router and create a router.
  • Use RouterLink for navigation.
  • Read params with useRoute.
  • Guard private routes with beforeEach.

In plain English

Vue Router maps URLs to components. Use history mode, typed route params and guards for authentication. Keep route components thin: fetch data in the page, keep the shared layout outside it.

router.jsJavaScript
import { createRouter, createWebHistory } from 'vue-router'
import Lessons from './Lessons.vue'
import Lesson from './Lesson.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/lessons', component: Lessons },
    { path: '/lessons/:slug', component: Lesson, props: true },
  ],
})

router.beforeEach((to) => {
  if (to.meta.private && !localStorage.getItem('token')) return '/login'
})

export default router
Your turn

Add a route param

Easy

Define a route /courses/:slug that renders a Course component and passes the param as a prop.

JAVASCRIPT · starter
{ path: '/courses/:slug', component: Course }
Check your understanding before moving on.
Knowledge checkQuestion 1

Which component should you use for in-app navigation?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 300 · 0% of course