In this short tutorial we will learn how to remove hash (#) from Url in Vue app with Vue-Router.
In Vuejs, a URL with a hashbang that looks like this :
/#/house
So in this article we will use the history Mode to change the url to this:
/house
Remove Hash from URL in Vue-Router 2.0 and 3.0
In Vue-Router 3.0, the default mode of vue-router
is hash mode i.e you will see the URL as /#/house .
The purpose of hashbang (#) is to initiate a file-path without having to setup any server configuration.
To get rid of the hash from the URL we have to change the mode of the router to history mode from hash mode in main.js file.
const router = new VueRouter({
mode: 'history',
routes: [...]
})
In main.js, we have a Vue Router instance with an object that have a route and a mode property. We just have to change the mode property to history.
So now whenever we visit a route eg /house, it will take us to /house
instead of /#/house
.
Remove Hashbang from URL in Vue Router 4.0
In Vue Router 4.0, the default mode of history will be createWebHashHistory()
. And just like the previous version, it will add a # internally to your URL.
To remove the hash we have to change the history from createWebHashHistory() to createWebHistory() in your router file.
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
//...
],
})
Note :
Since our app is a single page application without any proper server configuration, it will show us 404 error if we navigate to a nested URL
https://example.com/user/id
from our browser.So to solve this issue we will have to create a fall back route to the server. So if a URL doesn’t match a page it will show a default index.html page.
Create catch-all fallback route for Vue Router
To create a catch-all fallback route in Vue 2 and 3 add the following line in your Vue Router instance in main.js file.
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/:catchAll(.*)',
component: NotFoundComponent,
name: 'NotFound'
}
]
})
More details in this page.
And for Vue 3 and Vue Router 4 add the following line in the router file.
const router = createRouter({
history: createWebHistory(),
routes: [{ path: '/:pathMatch(.*)', component: NotFoundComponent }],
})
Related Topics:
Set URL Query Params In Vue Using Vue-Router
How To Redirect To External Url In Vue