JAVASCRIPT
Vue 3 Router: Basic Setup and Programmatic Navigation
Discover how to configure Vue Router for your Vue 3 application, define routes, and implement programmatic navigation to manage user flow and view transitions effectively.
// 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: '/user/:id',
name: 'user',
component: () => import('../views/UserView.vue'),
props: true // Pass route params as props to component
}
];
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
});
export default router;
// 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');
// components/NavigationMenu.vue (Example of programmatic navigation)
<template>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<button @click="goToUser(1)">Go to User 1</button>
</nav>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goToUser = (id) => {
router.push({ name: 'user', params: { id } });
// Alternatively: router.push(`/user/${id}`);
};
</script>
// App.vue
<template>
<NavigationMenu />
<router-view />
</template>
<script setup>
import NavigationMenu from './components/NavigationMenu.vue';
</script>
How it works: This snippet illustrates the fundamental setup of Vue Router in a Vue 3 application. It defines routes, including dynamic segments, and configures the router instance. The `main.js` file integrates the router with the application. A `NavigationMenu` component demonstrates both declarative navigation using `<router-link>` and programmatic navigation using `useRouter().push()` to direct users to different views.