0
0
Vueframework~5 mins

Vue Router installation and setup

Choose your learning style9 modes available
Introduction

Vue Router helps you move between different pages in your Vue app without reloading the page. It makes your app feel fast and smooth.

You want to create a website with multiple pages like Home, About, and Contact.
You want users to click links and see new content without the page refreshing.
You want to keep track of which page the user is on and show the right content.
You want to build a single-page app that feels like a normal website.
You want to add navigation menus that change the displayed content.
Syntax
Vue
import { createRouter, createWebHistory } from 'vue-router'
import Home from './components/Home.vue'

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

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

export default router

Use createRouter to make a router instance.

createWebHistory() uses normal browser history for clean URLs.

Examples
This example adds two pages: Home and About.
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
})

export default router
This example uses hash mode for URLs, which adds a # in the URL. It works without server setup.
Vue
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from './components/Home.vue'

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

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

export default router
Sample Program

This is a full Vue app setup with Vue Router. It shows two links and changes the page content without reloading.

Vue
<template>
  <div>
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </nav>
    <router-view />
  </div>
</template>

<script>
import { createRouter, createWebHistory } from 'vue-router'
import { createApp } from 'vue'

const Home = {
  template: '<h2>Home Page</h2>'
}

const About = {
  template: '<h2>About Page</h2>'
}

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

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

const app = createApp({})
app.use(router)
app.mount('#app')
</script>
OutputSuccess
Important Notes

Remember to install Vue Router first with npm install vue-router@4.

Use <router-link> for navigation links to keep the app fast.

<router-view> is where the current page content shows.

Summary

Vue Router lets you add pages and navigation to your Vue app.

Install it, create routes, and add router to your app.

Use <router-link> and <router-view> in your templates.