Vue.js - How to remove hashbang #! from url?

ghz 8months ago ⋅ 97 views

How to remove hashbang #! from url?

I found option to disable hashbang in vue router documentation ( http://vuejs.github.io/vue-router/en/options.html ) but this option removes #! and just put #

Is there any way to have clean url?

Example:

NOT: #!/home

BUT: /home

Answers

Yes, you can achieve clean URLs in Vue Router by using the mode option. The mode option determines the URL mode for the router. By default, Vue Router uses hash mode (mode: 'hash'), which results in URLs with # (hash) in them.

To remove the hashbang #! and have clean URLs without any hash or hashbang, you can use history mode (mode: 'history'). Here's how you can configure Vue Router to use history mode:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    // Define your routes here
  ]
})

export default router

With this configuration, your URLs will look like /home instead of #!/home. However, note that using history mode requires server-side configuration to properly handle routing for all your routes. Specifically, you need to ensure that your server is configured to serve the same HTML page for all routes so that Vue Router can handle the routing on the client-side.

For example, in a simple Express.js server, you would typically add a wildcard route to serve the same HTML file for all routes:

const express = require('express')
const path = require('path')
const app = express()

app.use(express.static(path.join(__dirname, 'public')))

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'))
})

app.listen(3000, () => {
  console.log('Server is running on port 3000')
})

Make sure to adjust the server configuration according to your specific server setup.