2
votes

There are an application, where routes handles by two sides: some routes handles by CMS, and some with vue-router. For example: http://localhost/ handles by CMS and webserver, but http://localhost/complex-page/#/my-route handles by both: CMS and Vue router.

That means It has two vue-router instances: global (just for use $route globaly, it use a history mode) and local (for using with hash mode). And here is a problem: local router behaves as if he overrides global mode and and hash adds to route everywhere, even there is no components with local routings.

Here is code that pretty close to real project:

let first = {
  name: "first",
  template: `<section><h1>First</h1></section>`
};


let second = {
  name: "second",
  template: `<section><h2>Second</h2></section>`
};

let outerComponent = Vue.component('container', {
  template: `
  <section>
    <h2>Outer</h2>
    <h3>Path: {{window.location.href}}</h3>
    <nav>
      <router-link to='/first' append>First</router-link>
      <router-link to='/second' append>Second</router-link>
    </nav> 
    <h3>Inner:</h3>
    <router-view></router-view>
  </section>
  `,
  router: new VueRouter({
    mode: 'hash', // HASH!!!
    components: {
      'first': first,
      'second': second
    },
    routes: [{
        path: "/first",
        component: first,
        name: "first"
      },
      {
        path: "/second",
        component: second,
        name: "second"
      }
    ]
  })
});


// Root!
new Vue({
  el: "#app",
  router: new VueRouter({
    mode: "history" // HISTORY!
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.1.3/vue-router.min.js"></script>

<div id="app">
  <!-- Even if delete this node, hash will be added -->
  <container></container>
</div>

How to disable the path's hash globally & add it in certain routes?

2

2 Answers

3
votes

You can disable the # globally by adding mode: 'history', like so:

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

You can read more in the official documentation.

EDIT:

If you want the # on a certain routes, you could accomplish it like so:

const router =
        new VueRouter({
            mode: 'history',
            routes: [
                {
                    path: "#/my-component-1",
                    component: MyComponent_1
                },
                {
                    path: "#/my-component-2",
                    component: MyComponent_2
                }
            ]
        });

export default {
        components: {
            // ... my routed components here
        },
        router
    }
1
votes

Just remove # enable history mode

new VueRoute({
    //...
    mode:'history'
   //....
})