How to remove hash from URL in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

Today I am going to show you How do you remove the hash(#) from the URL in the vue-router package in VueJS.

Table of contains

  • Setup the Vue (Optional)
  • Setup the vue-router
  • Remove hash(#) from URL from vue 2
  • Remove hash(#) from URL from vue 3

Let’s start today’s tutorial How do I remove the hash(#) from the URL in the vue-router package in VueJS?

Setup the Vue (Optional)

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Setup the vue-router

After the installation, of the vue project, Configure the vue-router module in your project. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation. It will also guide you, on how to show the router views using the router-view and how to use router-link.

How to configure or Install vue-router module in VueJS?

Remove hash(#) from URL from vue 2

As you can see, The hash is in the URL http://localhost:8080/#/ of the page. The hash is shown in every page link,

Hash in URL

To remove the Hash(#) from the URL, In vue 2 we have to use the mode: 'history' in the router as you can see in the example of VueJS 2:

import Vue from 'vue'
import Router from 'vue-router'


import ComponentName from '../components/ComponentName.vue'

Vue.use(Router)

const router = new Router({
    routes: [{
            path: 'path',
            component: ComponentName,
            name: 'Your Component Name'
        },

    ],
    mode: 'history'
})

export default router

Remove hash(#) from URL from vue 3

We have created the two components that are FirstComponent.vue & SecondComponent.vue

FirstComponent.vue

<template>
  <div>
    This is First Component.
  </div>
</template>
<script>
export default {
    name: 'FirstComponent',
}
</script>

SecondComponent.vue

<template>
  <div>
    This is Second Component.
  </div>
</template>
<script>
export default {
    name: 'SecondComponent',
}
</script>

In vue 3 we have import the createWebHistory then use the history: createWebHistory() code in your vue router module as you can see in the example of VueJS 3:

import { createWebHistory, createRouter } from "vue-router";
import FirstComponent from "@/components/FirstComponent.vue";
import SecondComponent from "@/components/SecondComponent.vue";

const routes = [
  {
    path: "/",
    name: "First",
    component: FirstComponent,
  },
  {
    path: "/second",
    name: "Second",
    component: SecondComponent,
  },
];

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

export default router;

For now, let’s check the output for Vue 3.

Output

Remove hash from URL

All the best 👍.

Follow me on Twitter