Lesson 06-Vue Router Management

Basic Usage

App.vue

<template>
  <h1>Hello App!</h1>
  <p>
    <strong>Current route path:</strong> {{ $route.fullPath }}
  </p>
  <nav>
    <RouterLink to="/">Go to Home</RouterLink>
    <RouterLink to="/about">Go to About</RouterLink>
  </nav>
  <main>
    <RouterView />
  </main>
</template>

Creating a Router Instance

In src/router/index.js, create a router instance and define route rules:

import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  }
];

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

export default router;

Here, two routes are defined: Home and About. Each route object includes a path for URL matching, a name for identification, and a component for the associated component.

Registering the Router Plugin

In the main application file (typically main.js or main.ts), register the router as a global plugin:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');

Accessing the Router and Current Route

In any component, access the router instance and current route information via this.$router and this.$route:

export default {
  methods: {
    navigateToAbout() {
      this.$router.push('/about');
    }
  },
  created() {
    console.log(this.$route);
  }
};
<script setup>
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();

const search = computed({
  get() {
    return route.query.search ?? '';
  },
  set(search) {
    router.replace({ query: { search } });
  }
});
</script>

Route Matching

Vue Router provides flexible route matching, including static and dynamic routes. Dynamic routes allow URL parameters for reusing components with different data.

Dynamic Route Matching

Defining Dynamic Routes

Dynamic routes use a colon (:) to define parameters in the path. For example, to display user profiles for different users:

const router = createRouter({
  routes: [
    { path: '/user/:id', component: UserProfileComponent }
  ]
});

Here, :id is a dynamic parameter matching any string. Visiting /user/123 or /user/john renders UserProfileComponent with id set to 123 or john.

Accessing Route Parameters

Access dynamic parameters via this.$route.params:

export default {
  computed: {
    userId() {
      return this.$route.params.id;
    }
  }
};

Using Parameters in Templates

Parameters can be used directly in templates:

<template>
  <div>
    <h1>User Profile: {{ $route.params.id }}</h1>
  </div>
</template>

Route Matching Syntax

Custom Regular Expressions

Define custom regular expressions for dynamic parameters to restrict formats. For example, to ensure :id is numeric:

const router = createRouter({
  routes: [
    {
      path: '/user/:id(\\d+)',
      component: UserProfileComponent
    }
  ]
});

Multiple Dynamic Parameters

Define multiple dynamic parameters in a single path:

const router = createRouter({
  routes: [
    { path: '/user/:id/post/:postId', component: PostComponent }
  ]
});

Access parameters in the component:

export default {
  computed: {
    userId() {
      return this.$route.params.id;
    },
    postId() {
      return this.$route.params.postId;
    }
  }
};

Passing Parameters as Props

Pass dynamic parameters as props to components for cleaner access:

const router = createRouter({
  routes: [
    { path: '/user/:id', component: UserProfileComponent, props: true }
  ]
});

Define props in the component:

export default {
  props: ['id'],
  computed: {
    userId() {
      return this.id;
    }
  }
};

Code Example

A complete example demonstrating these concepts:

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import UserProfileComponent from '../components/UserProfileComponent.vue';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/user/:id(\\d+)',
      component: UserProfileComponent,
      props: true
    }
  ]
});

export default router;
<!-- src/components/UserProfileComponent.vue -->
<template>
  <div>
    <h1>User Profile: {{ id }}</h1>
  </div>
</template>

<script>
export default {
  props: ['id']
};
</script>
// 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');

Membership Required

You must be a member to access this content.

View Membership Levels

Already a member? Log in here

Share your love