Vue Router is the routing library for Vue.js, designed to enable navigation in Single Page Applications (SPAs) without triggering full page reloads. Instead of reloading HTML files, Vue dynamically renders components based on the current URL, creating a fast, seamless, app-like experience. As your Vue application grows, a routing system becomes essential for managing multiple views, dynamic content, and URL-based state.

Installing Vue Router

Vue Router is not bundled with Vue by default and must be installed manually. Choose the version that matches your Vue setup:

For Vue 3 & 4:

code
npm install vue-router@4

For Vue 2:

code
npm install vue-router@3
code

Creating the Router Instance

Define a list of route records that map URL paths to Vue components. Then, create the router instance:

Example: Define Your Route-to-Component Mapping and Create a Router Instance

code
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

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

const router = createRouter({
history: createWebHistory(),
routes
})

export default router

Explanation:

  • createRouter() initializes the router.
  • createWebHistory() uses the browser’s History API for clean URLs.
  • The routes array defines path-to-component mappings.

Integrating Vue Router into the App

To enable routing in a Vue application, the router instance must be registered with the app during initialization. This connects the defined routes to the root component and activates Vue Router's internal navigation system.

Example: Activate Routing, Register the Router in Your main.js File

// main.js import { createApp } from 'vue' import App from './App.vue' import router from './router' const app = createApp(App) app.use(router) app.mount('#app')

Explanation:

  • app.use(router) enables routing across the app.
  • app.mount('#app') connects Vue to the root DOM element.

Rendering Route Components with <router-view>

In Vue Router, <router-view> displays the active route’s component. It serves as an outlet that updates whenever the route changes, allowing the layout to remain static while only the routed content updates.

Example: Use <router-view> in Your Layout to render the Component Associated with the Current Route

code
<template>
<div>
<Navbar />
<router-view />
</div>
</template>

Explanation:

  • <router-view> is a dynamic placeholder that updates as routes change.
  • It enables layouts to stay static while routed content is swapped dynamically.

Allow navigation between routes without reloading the page.<router-link> is a built-in Vue Router component that creates anchor elements bound to route paths. It updates the browser’s URL and triggers a route change through the Vue Router system.

Example: Use <router-link> Instead of Regular Anchor Tags to Handle Client-side Navigation Without Reloading

code
<template>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
</template>

Explanation:

  • Automatically intercepts clicks and updates the browser URL.
  • Supports active styling and accessibility out of the box.

Dynamic Route Parameters

Allow dynamic matching in route paths by using placeholders (e.g., : id). When a route with parameters is matched, the values are exposed in route.params for use inside the component.

Example: Handle Dynamic Segments in URLs using :paramName Syntax

code
// router/index.js
{ path: '/user/:id', component: UserProfile }
code

Example: To Access the Parameter Inside the Component

<!-- Inside UserProfile.vue --> <script setup> import { useRoute } from 'vue-router' const route = useRoute() const userId = route.params.id </script>

Explanation:

  • /user/42 will pass 42 as the id param.
  • useRoute() provides access to the current route and its params.

Working with Video in Vue Components

Vue components can handle embedded video playback using HTML5’s <video> tag. Video sources can be static or dynamic.

Static Video Embedding

Files placed in the public/ directory can be referenced in Vue templates using the <video> element. These files are served without being processed by the module system.

Example: To Embed Static Videos from the public/ Folder

code
<template>
<video controls width="100%">
<source src="/videos/sample.mp4" type="video/mp4" />
</video>
</template>

Explanation:

  • Files in public/ are served directly without being processed by Webpack or Vite.

Dynamic Video Binding with Props

Video source paths can be dynamically bound to props inside a Vue component. Enables the same component to load different videos based on external inputs without changing the component structure. The component receives a videoUrl prop and binds it to the <source> element using Vue’s template syntax.

Example: Pass a Video URL as a Prop to Make the Component Reusable

code
<template>
<video controls width="100%">
<source :src="videoUrl" type="video/mp4" />
</video>
</template>

<script setup>
defineProps({ videoUrl: String })
</script>

Explanation:

  • :src="videoUrl" binds the video source dynamically.
  • The videoUrl prop can come from a parent component or route.

Loading Video Using Route Parameters

When the route includes a dynamic segment (e.g., /video/:id), the useRoute() hook allows access to the params.id value can be used to construct the video file path at runtime. For dynamic video routes like /video/:id, retrieve the ID and use it to construct the source.

Example: Use Route Parameters to Build Dynamic Video Paths

code
// router/index.js
{ path: '/video/:id', component: VideoPlayer }
code
code
<!-- Inside VideoPlayer.vue -->
<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()
const videoUrl = `/videos/${route.params.id}.mp4`
</script>

<template>
<video controls width="100%">
<source :src="videoUrl" type="video/mp4" />
</video>
</template>

Explanation:

  • Visiting /video/lecture-1 loads /videos/lecture-1.mp4.

Programmatic Navigation to Video Routes

The useRouter() hook provides access to Vue Router’s navigation API. Using router.push(), the app can change routes programmatically, for example, to navigate to a video player view with a specific video ID.

Example: Navigate to a Specific Video Programmatically

code
import { useRouter } from 'vue-router'

const router = useRouter()
router.push('/video/lecture-1')

Explanation

  • useRouter() gives access to navigation functions.
  • router.push() changes routes programmatically.
  • Useful for navigating based on user actions without relying on <router-link>.