The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Install and use the router in Vue 3

posted on 2.2.2023 by Below Surface in "Vue.js"

The easiest way would be to set a check mark during the Vue 3 project initialization. However, if you missed that, it is easy to implement the router later on:

$ npm install vue-router@4

Within the main.ts file, add:

import router from './router

And add ".use(router)" to this line:

createApp(App).use(store).use(router).use(VueSmoothScroll).mount('#app')

In the App.vue template block, you can add components that should be rendered on every page, plus you add "<router-view />", so it may look like this:

<template>
  <BackgroundDiv />
  <NavigationButton />
  <NavigationBar />
  
  <router-view />
</template>

Then, within your views folder, you create all your pages as .vue files. In my case there is an "ImpressumPage.vue" Nothing additional needs to be added to those pages, besides the HTML.

The navigation links have to look like this:

<router-link to="/impressum">Impressum</router-link>

And finally, you create a folder within /src named "router" and add an index.ts file with the following content:

import { createRouter, createWebHistory } from "vue-router";
import HomePage from "../views/HomePage.vue";
import ImpressumPage from "../views/ImpressumPage.vue";

const routes = [     {         path: "/",         name: "Home",         component: HomePage     },     {         path: "/impressum",         name: "Impressum",         component: ImpressumPage     } ];

const router = createRouter({     history: createWebHistory(process.env.BASE_URL),     routes, });

export default router;

Now, restart the local development server and it should work! Watch the video tutorials of the provided resource for more info.


Update: For sure, in most cases you want to scroll to the top of the page, when navigation to a new one. Just add these lines to the router/index.ts file where the router is created with createRouter({}):

scrollBehavior() {
    return { top: 0 }
},

Tags:

vue.js
vue 3
router
page navigation

Sources:

https://router.vuejs.org/guide/https://router.vuejs.org/guide/advanced/scroll-behavior.html

More posts of this category

Getting started with global state management in Vue.js

How to use the Vue.js global store called Vuex

Vue.js

Building a custom image slider in Vue.js

From a Vue.js newbie: How to build a custom image slider

Vue.js

Add smooth scrolling to a Vue 3 website

Adding smooth scrolling usually makes up for a much better UX, and it is easy to implement

Vue.js

How to send emails from a Vue 3 client app

Learn how to use Emailjs to send emails from your client app

Vue.js