Categories
Vue 3

How to Remove the Hash from the URL with Vue Router 4?

Spread the love

Sometimes, we want to map our components to paths that don’t have a hash in front of it in our Vue 3 app that uses Vue Router 4.

In this article, we’ll look at how to remove the hash from the URL path with Vue Router 4.

Remove the Hash from the URL with Vue Router 4

We can remove the hash from the URLs with Vue Router 4 by calling the createWebHistory method.

For instance, we can write:

main.js

import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import Page1 from "./views/Page1";
import Page2 from "./views/Page2";
import Page3 from "./views/Page3";

const routes = [
  { path: "/", component: Page1 },
  { path: "/page2", component: Page2 },
  { path: "/page3", component: Page3 }
];

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

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

App.vue

<template>
  <router-link to="/">page 1</router-link>
  <router-link to="/page2">page 2</router-link>
  <router-link to="/page3">page 3</router-link>
  <router-view></router-view>
</template>

<script>
export default {
  name: "App"
};
</script>

views/Page1.vue

<template>
  <div>page 1</div>
</template>

views/Page2.vue

<template>
  <div>page 2</div>
</template>

views/Page3.vue

<template>
  <div>page 3</div>
</template>

In main.js , we have the routes array with the route definitions.

We map the URL paths to components.

Then we call createRouter with an object that has the history property set to value returned by createWebHistory .

createWebHistory set the router to HTML5 history mode to remove the hash.

This will remove the hash from the paths that are mapped by Vue Router 4.

We also set the routes property to the routes array to add the routes we created.

Next, we call app.use with router to add the router object.

In App.vue , we have the router-link s to render the links.

router-view render the route page components.

Page1 , Page2 and Page3 are route components.

Now when we click on the router links, we shouldn’t see the hash in between the hostname and the route paths.

Conclusion

We can remove the hash from the URL with Vue Router 4’s createWebHistory function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *