Hash模式与History模式区别
前端路由中,不管是什么实现模式,都是客户端的一种实现方式,也就是当路径发生变化的时候,是不会向服务器发送请求的。
如果需要向服务器发送请求,需要用到ajax
方式。
两种模式的区别
首先是表现形式的区别
Hash
模式
https://www.baidu.com/#/showlist?id=22256
hash
模式中路径带有#
, #
后面的内容作为路由地址。可以通过问号携带参数。
当然这种模式相对来说比较丑,路径中带有与数据无关的符号,例如#
与?
History
模式
https://www.baidu.com/showlist/22256
History
模式是一个正常的路径的模式,如果要想实现这种模式,还需要服务端的相应支持。
下面再来看一下两者原理上的区别。
Hash
模式是基于锚点,以及onhashchange
事件。
通过锚点的值作为路由地址,当地址发生变化后触发onhashchange
事件。
History
模式是基于HTML5
中的History API
也就是如下两个方法
history.pushState( )
IE10
以后才支持
history.replaceState( )
13.2 History
模式的使用
History
模式需要服务器的支持,为什么呢?
因为在单页面的应用中,只有一个页面,也就是index.html
这个页面,服务端不存在http://www.test.com/login
这样的地址,也就说如果刷新浏览器,
请求服务器,是找不到/login
这个页面的,所以会出现404
的错误。(在传统的开发模式下,输入以上的地址,会返回login
这个页面,而在单页面应用中,只有一个页面为index.html
)
所以说,在服务端应该除了静态资源外都返回单页应用的index.html
下面我们开始history
模式来演示一下对应的问题。
首先添加一个针对404组件的处理
首先在菜单栏中添加一个链接:
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li><router-link to="/users"> 用户管理</router-link></li>
<li><router-link to="/rights"> 权限管理</router-link></li>
<li><router-link to="/goods"> 商品管理</router-link></li>
<li><router-link to="/orders"> 订单管理</router-link></li>
<li><router-link to="/settings"> 系统设置</router-link></li>
<li><router-link to="/about"> 关于</router-link></li>
</ul>
</div>
这里我们添加了一个“关于”的链接,但是我们没有为其定义相应的组件,所以这里需要处理404的情况。
const NotFound = {
template: `<div>
你访问的页面不存在!!
</div>`,
};
在程序中添加了一个针对404的组件。
const router = new VueRouter({
mode: "history",
const router = new VueRouter({
mode: "history",
routes: [
{ path: "/login", component: Login },
{ path: "*", component: NotFound },
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
// beforeEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
在上面的代码中,指定了处理404的路由规则,同时将路由的模式修改成了history
模式。同时,启用这里启用了其它的组件的路由规则配置,也就是不在login
方法中使用addRoutes
方法来动态添加路由规则了。
login
方法修改成如下形式:
login() {
// window.isLogin = true;
window.sessionStor