Prevent location change in browser url in VueJs

不羁的心 提交于 2019-12-13 00:56:32

问题


I have a vuejs application where i make rest api calls to the backend. I have define the router and navigate the different components. Now as I navigate i see the https://domain-name.com/#/abc the route path in the browser URL. I want to prevent this so that it always show https://domain-name.com/ irrespective of what path i traverse. Is there a way to do it in Vuejs or any other solution. Appreciate you help!

Thanks, Rahul


回答1:


You're using Vue Router, the idea of it to change routes...

Since you've got the Hash in the url under your router you'll need to add mode attribute.

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

This will remove the /#/someRoute and it will become /someRoute

Once adding history mode, you'll need to setup your apache/nginx server up respectively to reflect if the user was to type in domain.com/someRoute they would receive nothing which we can fix here.

If you want the link to permanently stay as www.domain.com instead of using vue-router, you'll have to change components as and when you need them essentially having a million and one if statements on the page.




回答2:


You can use alias

An alias of /a as /b means when the user visits /b, the URL remains /b, but it will be matched as if the user is visiting /a.

The above can be expressed in the route configuration as:

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

So, in your case

const router = new VueRouter({
  routes: [
  // the URL will remains https://domain-name.com/
    { path: '/abc', component: ABC, alias: '/' }
    { path: '/def', component: DEF, alias: '/' }
  ]
})


来源:https://stackoverflow.com/questions/50621920/prevent-location-change-in-browser-url-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!