← Back to all snippets
JAVASCRIPT

Vue 3 Vue Router Basic Setup and Programmatic Navigation

Learn the fundamental setup of Vue Router in a Vue 3 application, defining routes, using router-link and router-view, and performing programmatic navigation.

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import AboutView from '../views/AboutView.vue';

const routes = [
  { path: '/', name: 'Home', component: HomeView },
  { path: '/about', name: 'About', component: AboutView },
  { path: '/users/:id', name: 'User', component: () => import('../views/UserView.vue') } // Lazy-loaded route
];

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

export default router;

// src/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');

// src/App.vue
<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <router-view />
  <button @click="goToUser(123)">Go to User 123</button>
</template>

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

function goToUser(id) {
  router.push({ name: 'User', params: { id } });
}
</script>

// src/views/HomeView.vue (example)
<template>
  <h1>Home Page</h1>
  <p>Welcome to the home page!</p>
</template>
<script setup></script>

// src/views/AboutView.vue (example)
<template>
  <h1>About Page</h1>
  <p>This is the about page.</p>
</template>
<script setup></script>

// src/views/UserView.vue (example)
<template>
  <h1>User Page</h1>
  <p>Displaying user with ID: {{ $route.params.id }}</p>
</template>
<script setup></script>
How it works: This snippet provides a comprehensive guide to setting up Vue Router in a Vue 3 application. It demonstrates defining routes, integrating the router with the main Vue app, using `<router-link>` for declarative navigation, `<router-view>` for displaying component based on the current route, and performing programmatic navigation using `router.push()` to navigate to named routes with parameters.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs