如何删除hashbang #!从url ?

我在vue路由器文档(http://vuejs.github.io/vue-router/en/options.html)中找到了禁用hashbang的选项,但这个选项删除了#!然后输入#

有没有办法有干净的url?

例子:

不是:# !/家庭

但是:/家庭

谢谢!


当前回答

引用文档。

vue-router的默认模式是哈希模式-它使用URL哈希来 模拟一个完整的URL,这样页面将不会被重新加载的URL 的变化。 为了摆脱散列,我们可以使用路由器的历史模式 利用历史。pushState API实现URL导航 页面重载:

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

When using history mode, the URL will look "normal," e.g. http://oursite.com/user/id. Beautiful! Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser. Now that's ugly. Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!

其他回答

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

如果您正在使用AWS amplify,请查看关于如何配置服务器的本文:Vue路由器的历史模式和AWS amplify

在Vue 3中,你需要使用createWebHistory作为历史选项。

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  // ...
})

在Vue 2中,你需要将模式设置为“历史”。

const router = new VueRouter({
  mode: 'history',
  // ...
})

但是,请确保您的服务器配置为处理这些链接。 https://router.vuejs.org/guide/essentials/history-mode.html

上面的几个很好的描述把我带进了兔子洞,直到我意识到“createWebHistory”取代了“createWebHashHistory”存在于router/index.js文件的两个地方。一次是在文件末尾的常量定义中,一次是在文件顶部的vue-router导入中。

在router/index.js文件的末尾找到

  const router = createRouter({
    mode: 'history',
    history: createWebHistory(),
    // history: createWebHashHistory(),
    routes
  })

router/index.js文件的第一行

import { createRouter, createWebHistory } from 'vue-router'
// import { createRouter, createWebHashHistory } from 'vue-router'

现在它就像一个魅力,感谢上面所有的人指引我走上这条成功之路!

在Vue 3中,您可以使用Vue -router包提供的createWebHistory模块来获得一个干净的URL。

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  // ...
})

还有另一个模块在名为createWebHashHistory的URL中保存“#”符号,它帮助浏览器导航到特定的元素。

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  // ...
})

如果你不想在URL中使用'#'符号,你可能更喜欢使用createWebHistory而不是createWebHashHistory。

要了解更多信息,请查看他们的文档: https://router.vuejs.org/guide/essentials/history-mode.html

打开src->router->index.js文件

在这个文件的底部:

const router = new VueRouter({
  mode: "history",
  routes,
});