当前位置: 博客 /  JavaScript  / 去掉URL后的哈希符号(井号#)

一、问题

运行reac项目时,有可能在URL后方跟随着一个哈希符号(井号#),例如:

http://localhost:3000/#/

二、解决方法

2.1 react-router

引入 BrowserRouter作为Router。或在项目中找到引入 HashRouter 的地方,替换为 BrowserRouter

例如:

import { HashRouter as Router } from 'react-router-dom';

改为:

import { BrowserRouter as Router } from "react-router-dom";

2.2 vue-router

给Router加上模式mode为history。

例如:

import Router from 'vue-router'
export default new Router({
    mode: 'history',    //此处mode修改为history
    routes: [
        {
            path: '/',
            name: 'Home',
            component: Home,
        }
    ]
})

三、原理

查阅react-router的相关API得知:

3.1 BrowserRouter

3.1.1 释义

A <Router> that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL.

BrowserRouter使用的是HTML5 history API,具有pushState、replaceState方法和popstate事件,来确保你的UI界面与URL同步。

3.1.2 举例

<BrowserRouter basename="/calendar" />
<Link to="/today"/>     // 渲染为:<a href="/calendar/today">

3.2 HashRouter

3.2.1 释义

A <Router> that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.

HashRouter使用URL的哈希(hash)部分(即window.location.hash),来确保你的UI界面与URL同步。

3.2.2 重要提示

在HashRouter释义下方有一条重要提示:

IMPORTANT NOTE: Hash history does not support location.key or location.state. In previous versions we attempted to shim the behavior but there were edge-cases we couldn’t solve. Any code or plugin that needs this behavior won’t work. As this technique is only intended to support legacy browsers, we encourage you to configure your server to work with <BrowserHistory> instead.

翻译:哈希历史不支持location.key或location.state。在以前的版本中我们试图修补,但有一些边角情况我们无法解决。任何需要此行为的代码或插件都无法工作。由于此技术仅用于支持传统浏览器,因此我们建议您将服务器配置为使用 <BrowserHistory>。

3.2.3 举例

<HashRouter basename="/calendar"/>
<Link to="/today"/>     // 渲染为:<a href="#/calendar/today">  **注意此处渲染结果有哈希符号(井号#)

四、相关资料

react-router

vue-router

BrowserRouter

HashRouter

HTML5 history API

window.location

- END -