Bird
Raised Fist0
Vueframework~10 mins

Defining routes in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Defining routes
Start Vue app
↓
Create router instance
↓
Define routes array
↓
Pass routes to router
↓
Mount router to app
↓
User navigates URL
↓
Router matches route
↓
Render matched component
↓
Display page content
This flow shows how Vue Router sets up routes and renders components based on the URL.
Execution Sample
Vue
import { createRouter, createWebHistory } from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

const router = createRouter({ history: createWebHistory(), routes })
This code defines two routes and creates a router instance with history mode.
Execution Table
StepActionInput/StateOutput/Result
1Import router functionsN/AcreateRouter and createWebHistory available
2Define routes arrayEmpty routesroutes = [{path:'/',component:Home},{path:'/about',component:About}]
3Create router instanceroutes arrayrouter with history and routes configured
4Mount router to approuter instanceApp uses router for navigation
5User navigates to '/'URL = '/'Router matches '/' route
6Render matched componentMatched route '/'Home component displayed
7User navigates to '/about'URL = '/about'Router matches '/about' route
8Render matched componentMatched route '/about'About component displayed
9User navigates to '/contact'URL = '/contact'No match found, fallback or 404
10Render fallbackNo matched routeShow 404 or redirect
11EndNo more navigationApp stays on current page
💡 Execution stops when user stops navigating or app closes.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
routesundefined[{path:'/',component:Home},{path:'/about',component:About}][same][same][same]
routerundefinedundefinedrouter instance createdrouter mounted to approuter active
URLundefinedundefinedundefineduser navigates '/'changes with navigation
Key Moments - 3 Insights
Why do we need to define routes as an array of objects?
Because Vue Router uses this array to know which URL path matches which component to display, as shown in execution_table rows 2 and 3.
What happens if the user navigates to a URL not defined in routes?
The router finds no match and shows a fallback or 404 page, as seen in execution_table rows 9 and 10.
Why do we use createWebHistory() when creating the router?
It enables clean URLs without hashes, managing browser history properly, as shown in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what component is displayed when the URL is '/'?
A404 fallback
BAbout component
CHome component
DNo component
💡 Hint
Check execution_table row 6 where URL '/' matches Home component.
At which step does the router instance get created?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Look at execution_table step 3 where router instance is created.
If we add a new route for '/contact', what changes in the execution table?
AThe router instance creation step changes
BA new row for '/contact' navigation and rendering appears
CThe routes array becomes empty
DNo changes happen
💡 Hint
Adding a route affects navigation steps, see rows 5-8 for existing routes.
Concept Snapshot
Defining routes in Vue Router:
- Create an array of route objects: { path, component }
- Use createRouter with history and routes
- Mount router to Vue app
- Router matches URL to route
- Displays matched component
- Handles unmatched URLs with fallback
Full Transcript
This visual execution shows how Vue Router defines routes and renders components. First, we import router functions, then define routes as an array with path and component pairs. Next, we create a router instance using createRouter and createWebHistory. The router is mounted to the Vue app. When a user navigates to a URL, the router matches it to a route and renders the corresponding component. If no route matches, a fallback or 404 page is shown. Variables like routes and router instance change as the app initializes and runs. Key moments include understanding the routes array, handling unmatched URLs, and the role of history mode. The quizzes test knowledge of component rendering, router creation step, and adding new routes.

Practice

(1/5)
1. What is the main purpose of defining routes in a Vue application?
easy
A. To style components with CSS
B. To connect URLs to components so different pages can be shown
C. To manage state between components
D. To handle user input events

Solution

  1. Step 1: Understand the role of routes

    Routes link specific URLs to Vue components, allowing navigation between pages.
  2. Step 2: Identify the correct purpose

    Connecting URLs to components matches the description of routing.
  3. Final Answer:

    To connect URLs to components so different pages can be shown -> Option B
  4. Quick Check:

    Routes = URL to component mapping [OK]
Hint: Routes map URLs to components for page navigation [OK]
Common Mistakes:
  • Confusing routes with styling or CSS
  • Thinking routes manage state or events
  • Mixing routes with user input handling
2. Which of the following is the correct way to define a route for path '/home' using a component named HomeView?
easy
A. { path: '/home', component: HomeView }
B. { route: '/home', view: HomeView }
C. { url: '/home', component: HomeView }
D. { path: '/home', view: HomeView }

Solution

  1. Step 1: Recall route object keys

    Routes use keys 'path' for URL and 'component' for the Vue component.
  2. Step 2: Match correct syntax

    { path: '/home', component: HomeView } uses correct keys: path and component with proper values.
  3. Final Answer:

    { path: '/home', component: HomeView } -> Option A
  4. Quick Check:

    Route keys = path + component [OK]
Hint: Use 'path' and 'component' keys to define routes [OK]
Common Mistakes:
  • Using 'route' or 'url' instead of 'path'
  • Using 'view' instead of 'component'
  • Mixing keys or misspelling them
3. Given this route setup:
const routes = [
  { path: '/', component: HomeView },
  { path: '/about', component: AboutView }
];
const router = createRouter({
  history: createWebHistory(),
  routes
});
What component will show when the URL is '/about'?
medium
A. AboutView
B. HomeView
C. createRouter
D. createWebHistory

Solution

  1. Step 1: Check the route matching '/about'

    The route with path '/about' uses component AboutView.
  2. Step 2: Understand router behavior

    When URL is '/about', Vue Router renders AboutView component.
  3. Final Answer:

    AboutView -> Option A
  4. Quick Check:

    URL '/about' shows AboutView [OK]
Hint: URL matches route path to show its component [OK]
Common Mistakes:
  • Confusing router functions with components
  • Choosing HomeView for '/about' URL
  • Not linking URL to correct route
4. Identify the error in this route definition:
const routes = [
  { path: '/contact', component ContactView }
];
medium
A. Component name should be a string
B. Path should start with '#' instead of '/'
C. Missing colon ':' after 'component'
D. Routes array should be inside createRouter

Solution

  1. Step 1: Check object syntax in route

    Each key-value pair must have a colon ':' separating them.
  2. Step 2: Spot missing colon after 'component'

    In the route, 'component ContactView' misses ':'; it should be 'component: ContactView'.
  3. Final Answer:

    Missing colon ':' after 'component' -> Option C
  4. Quick Check:

    Object syntax needs ':' [OK]
Hint: Check colons between keys and values in objects [OK]
Common Mistakes:
  • Forgetting colon ':' in object properties
  • Using '#' instead of '/' in paths
  • Putting component names as strings incorrectly
5. You want to create a Vue router with two routes: '/' showing HomeView and '/profile/:id' showing ProfileView. Which code correctly defines these routes and sets up the router?
hard
A. const routes = [ { path: '/', component: HomeView }, { path: '/profile/:id', component: ProfileView } ]; const router = createRouter({ history: createMemoryHistory(), routes });
B. const routes = [ { path: '/', component: HomeView }, { path: '/profile/id', component: ProfileView } ]; const router = createRouter({ history: createWebHistory(), routes });
C. const routes = [ { path: '/', component: HomeView }, { path: '/profile/:id', component: 'ProfileView' } ]; const router = createRouter({ history: createWebHistory(), routes });
D. const routes = [ { path: '/', component: HomeView }, { path: '/profile/:id', component: ProfileView } ]; const router = createRouter({ history: createWebHistory(), routes });

Solution

  1. Step 1: Define routes with dynamic segment

    Use '/profile/:id' to capture dynamic id parameter correctly.
  2. Step 2: Use correct component references and history mode

    Components must be variables (not strings). Use createWebHistory() for normal web routing.
  3. Step 3: Check each option

    const routes = [ { path: '/', component: HomeView }, { path: '/profile/:id', component: ProfileView } ]; const router = createRouter({ history: createWebHistory(), routes }); matches all requirements: dynamic path, component variables, and web history.
  4. Final Answer:

    Correct route array with dynamic segment and createWebHistory() -> Option D
  5. Quick Check:

    Dynamic routes use ':param' and createWebHistory() [OK]
Hint: Use ':param' for dynamic routes and createWebHistory() for browser routing [OK]
Common Mistakes:
  • Using literal 'id' instead of ':id' for dynamic segments
  • Passing component names as strings instead of variables
  • Using createMemoryHistory() instead of createWebHistory() for web apps
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard