If we’re using Vue Router, then by default, the URL generated from a component has the hashbang in it.
In this article, we’ll look at how to remove a hashbang from a URL in a Vue.js app.
History Mode
We can remove the hashbang from a URL if we set Vue Router to history mode.
For instance, we can write:
main.js
import Vue from "vue";
import App from "./App.vue";
import HelloWorld from "./views/HelloWorld.vue";
import VueRouter from "vue-router";
const routes = [{ path: "/hello", component: HelloWorld }];
Vue.config.productionTip = false;
Vue.use(VueRouter);
const router = new VueRouter({
routes,
mode: "history"
});
new Vue({
render: (h) => h(App),
router
}).$mount("#app");
App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App",
};
</script>
views/HelloWorld.vue
<template>
<div class="hello">
<h1>hello world</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
name: "",
};
},
};
</script>
In main.js
, we create the VueRouter
instance with an object that has the routes
property.
And also, we have the mode
property set to 'history'
.
How we can go to the /hello
path without the hash.
So instead of going to /#/hello
, we go to /hello
.
To make this work, the server has to be properly configured.
For example, if we’re using an Apache server, then we’ve configure the server to go to index.html
when we go to any URL.
This way, the Vue app will be loaded instead of other things in the server since index.html
is the home page of a Vue app if the Vue app is deployed to the server.
For instance, we can write:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
With Nginx, we configure our server by writing:
location / {
try_files $uri $uri/ /index.html;
}
Other configs are available at https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations.
Conclusion
We can remove the hashbang from a URL by making Vue Router use history mode instead of the default hash mode.