Vue.js Router

Implementing routing with Vue Router

Router Setup

import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
    history: createWebHistory(),
    routes: [
        { path: '/', component: Home }
    ]
});

Route Definition

routes: [
    { path: '/', component: Home }, # basic route
    { path: '/about', component: About },
    { path: '/user/:id', component: User }, # dynamic route
    { path: '/*', component: NotFound } # catch-all
]

Router Links

<router-link to="/">Home</router-link> # declarative navigation
<router-link :to="`/user/${id}`">User</router-link> # dynamic

Programmatic Navigation

this.$router.push('/home'); # navigate
this.$router.replace('/home'); # replace history
this.$router.go(-1); # go back

Route Parameters

this.$route.params.id # access param
this.$route.query.search # access query

Named Routes

{ path: '/user/:id', name: 'user', component: User }
<router-link :to="{name: 'user', params: {id: 1}}">User</router-link>