路由是根据不一样的url地址来显示不一样的页面或内容的功能,这个概念很早是由后端提出的。 后端以前是这么作的,当咱们访问 xxx.abc.com/xx 的时候,大体流程能够想象成这样的:html
如上就是后端路由最初始的实现方式,那么既然有后端路由,那为何还须要咱们前端路由呢?后端路由有一个很大的缺点就是每次路由切换的时候都须要去刷新页面,而后发出ajax请求,而后将请求数据返回回来,那么这样每次路由切换都要刷新页面对于用户体验来讲就很差了。所以为了提高用户体验,咱们前端路由就这样产生了。它就能够解决浏览器不会从新刷新了。前端
在理解路由以前,咱们下面看下History API有哪些方法: DOM window对象经过history对象提供了对当前会话浏览历史的访问,在html4中有以下方法:html5
window.history.length: 返回当前会话浏览过的页面数量。node
window.history.go(?delta): 接收一个整数做为参数,按照当前页面在会话浏览历史记录中的位置进行移动。若是参数为0、undefined、null、false 将刷新页面,至关于执行window.location.reload()方法。若是参数大于浏览器浏览的数量,或小于浏览前的数量的话,什么都不会作。webpack
window.history.back(). 移动到上一页。至关于点击浏览器的后退按钮,等价于 window.history.go(-1);es6
window.history.forward(). 移动到下一页,至关于点击浏览器的前进按钮,等价于window.history.go(1).web
在html5中,History API 新增了操做会话浏览历史记录的功能。以下新增的几个方法:ajax
window.history.state. 该参数是只读的,表示与会话浏览历史的当前记录相关联的状态对象。以下图所示:json
window.history.pushState(data, title, ?url): 在会话浏览历史记录中添加一条记录。后端
window.history.replaceState(data, title, ?url): 该方法用法和history.pushState方法相似,可是该方法的含义是将修改会话浏览历史的当前记录,而不是新增一条记录。也就是说把当前的浏览地址换成 replaceState以后的地址,可是浏览历史记录的总长度并无新增。
注意:执行上面两种方法后,url地址会发生改变。可是不会刷新页面。所以有了这些基本知识后,咱们再来看下前端路由。
那么前端路由也有2种模式,第一种是hash模式,第二种是history模式。咱们来分别看下这两种知识点及区别以下:
hash路由模式是这样的:xxx.abc.com/#/xx。 有带#号,后面就是hash值的变化。改变后面的hash值,它不会向服务器发出请求,所以也就不会刷新页面。而且每次hash值发生改变的时候,会触发hashchange事件。所以咱们能够经过监听该事件,来知道hash值发生了哪些变化。好比咱们能够以下简单的监听:
function hashAndUpdate () {
// todo 匹配 hash 作 dom 更新操做
}
window.addEventListener('hashchange', hashAndUpdate);
复制代码
咱们先来了解下location有哪些属性,以下:
// 完整的url
location.href
// 当前URL的协议,包括 :; 好比 https:
location.protocol
/* 主机名和端口号,若是端口号是80(http)或443(https), 那就会省略端口号,比兔 www.baidu.com:8080 */
location.host
// 主机名:好比:www.baidu.com
location.hostname
// 端口号;好比8080
location.port
// url的路径部分,从 / 开始; 好比 https://www.baidu.com/s?ie=utf-8,那么 pathname = '/s'了
location.pathname
// 查询参数,从?开始;好比 https://www.baidu.com/s?ie=utf-8 那么 search = '?ie=utf-8'
location.search
// hash是页面中的一个片断,从 # 开始的,好比 https://www.baidu.com/#/a/b 那么返回值就是:"#/a/b"
location.hash
复制代码
location.href
咱们经过改变location.href来改变对应的url,看看是否会刷新页面,咱们作以下测试能够看到,使用location.href 改变url后并不会刷新页面,以下代码在控制台中演示:
location.hash
改变hash不会触发页面跳转,由于hash连接是当前页面中的某个片断,因此若是hash有变化,那么页面将会滚动到hash所链接的位置。可是页面中若是不存在hash对应的片断,则没有任何效果。好比 a连接。这和 window.history.pushState方法相似,都是不刷新页面的状况下更改url。以下也能够看到操做并无刷新url,以下演示:
hash 和 pushState 对比有以下缺点:
hash只能修改url的片断标识符的部分。而且必须从#号开始,可是pushState且能修改路径、查询参数和片断标识符。pushState比hash更符合前端路由的访问方式,更加优雅(由于不带#号)。
hash必须和原先的值不一样,才能新增会话浏览历史的记录,可是pushState能够新增相同的url的记录,以下所示:
1.1 使用hashchange事件来监听url hash的改变
咱们来演示下,咱们使用node启动一个服务,而后有一个index.html页面,该页面引入了一个js文件,该js文件有以下js代码:
window.addEventListener('hashchange', function(e) {
console.log(e)
});
复制代码
如上代码就是监听hash值发生变化的事件,而后咱们访问该index.html页面后,而后在控制台中,作以下操做,以下图演示:
如上能够看到;无论咱们是经过location接口直接改变hash值,仍是咱们经过history直接前进或后退操做(改变hash变化),咱们均可以看到都能经过 hashchange该事件进行监听到url hash的改变。而且不会刷新页面。
HTML5的History API为浏览器的全局history对象增长了该扩展方法。它是一个浏览器的一个接口,在window对象中提供了onpopstate事件来监听历史栈的改变,只要历史栈有信息发生改变的话,就会触发该事件。提供了以下事件:
window.addEventListener('popstate', function(e) {
console.log(e)
});
复制代码
history提供了两个操做历史栈的API: history.pushState 和 history.replaceState
history.pushState(data[,title][,url]); // 向历史记录中追加一条记录
history.replaceState(data[,title][,url]); // 替换当前页在历史记录中的信息。
如上html5中新增了上面这两个方法,该两个方法也能够改变url,页面也不会从新刷新。下面咱们也能够来作个demo,来监听下popstate事件,如今在我js里面放入以下js代码:
window.addEventListener('popstate', function(e) {
console.log(e)
});
复制代码
而后咱们访问页面,以下所示:
如上图所示,咱们使用location.hash, history.go(-1), history.pushState 等方法操做都会触发 popstate 事件,而且浏览器的url地址也会跟着改变。只会改变url地址,且不会从新刷新页面。
hash模式的特色:
hash模式在浏览器地址栏中url有#号这样的,好比(http://localhost:3001/#/a). # 后面的内容不会传给服务端,也就是说不会从新刷新页面。而且路由切换的时候也不会从新加载页面。
history模式的特色:
浏览器地址没有#, 好比(http://localhost:3001/a); 它也同样不会刷新页面的。可是url地址会改变。
****实现hash路由须要知足以下基本条件:
触发hash值的变化有2种方法:
第一种是经过a标签,设置href属性,当点击a标签以后,地址栏会改变,同时会触发hashchange事件。好比以下a连接:
<a href="#/test1">测试hash1</a>
复制代码
第二种是经过js直接赋值给location.hash,也会改变url,触发hashchange事件。
location.hash = '#/test1';
复制代码
所以咱们下面能够实现一个简单的demo,html代码以下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hash路由demo</title>
</head>
<body>
<ul>
<li><a href="#/">我是主页</a></li>
<li><a href="#/a">我是a页面</a></li>
<li><a href="#/b">我是b页面</a></li>
</ul>
</body>
</html>
复制代码
而后咱们hash.js 代码以下:
class HashRouter {
constructor() {
// 存储hash与callback键值对
this.routes = {};
// 保存当前的hash
this.currentHash = '';
// 绑定事件
const hashChangeUrl = this.hashChangeUrl.bind(this);
// 页面加载事件
window.addEventListener('load', hashChangeUrl, false);
// 监听hashchange事件
window.addEventListener('hashchange', hashChangeUrl, false);
}
// path路径和callback函数对应起来,而且使用 上面的this.routes存储起来
route(path, callback) {
this.routes[path] = callback || function() {};
}
hashChangeUrl() {
/*
获取当前的hash值
location.hash 获取的值为:"#/a, 所以 location.hash.slice(1) = '/a' 这样的 */ this.currentHash = location.hash.slice(1) || '/'; // 执行当前hash对应的callback函数 this.routes[this.currentHash](); } } // 初始化 const Router = new HashRouter(); const body = document.querySelector('body'); const changeColor = function(color) { body.style.backgroundColor = color; }; // 注册函数 Router.route('/', () => { changeColor('red'); }); Router.route('/a', () => { changeColor('green'); }); Router.route('/b', () => { changeColor('#CDDC39'); }); 复制代码
如上就是一个很是简化的hash路由了,首先咱们代码也是很是的简化(我相信你们都能看懂),首先如上js代码有一个route函数,该函数的做用就是初始化对应的路由和函数进行绑定起来,把他们保存到 this.routes 对象里面去,而后使用 hashchange 事件进行监听,若是触发了该事件,就找到该路由,而后触发对应的函数便可。咱们点击某个a连接就会调用对应的函数,或者咱们能够在控制台中使用 location.hash = '/b'; 来改变值也会触发的。
三:如何实现简单的history路由?*
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hash路由demo</title>
</head>
<body>
<ul>
<li><a href="/">我是主页</a></li>
<li><a href="/a">我是a页面</a></li>
<li><a href="/b">我是b页面</a></li>
</ul>
</body>
</html>
复制代码
class HistoryRoutes {
constructor() {
// 保存对应键和函数
this.routes = {};
// 监听popstate事件
window.addEventListener('popstate', (e) => {
const path = this.getState();
this.routes[path] && this.routes[path]();
});
}
// 获取路由路径
getState() {
const path = window.location.pathname;
return path ? path : '/';
}
route(path, callback) {
this.routes[path] = callback || function() {};
}
init(path) {
history.replaceState(null, null, path);
this.routes[path] && this.routes[path]();
}
go(path) {
history.pushState(null, null, path);
this.routes[path] && this.routes[path]();
}
}
window.Router = new HistoryRoutes();
console.log(location.pathname);
Router.init(location.pathname);
const body = document.querySelector('body');
const changeColor = function(color) {
body.style.backgroundColor = color;
};
// 注册函数
Router.route('/', () => {
changeColor('red');
});
Router.route('/a', () => {
changeColor('green');
});
Router.route('/b', () => {
changeColor('#CDDC39');
});
const ul = document.querySelector('ul');
ul.addEventListener('click', e => {
console.log(e.target);
if (e.target.tagName === 'A') {
e.preventDefault();
Router.go(e.target.getAttribute('href'));
}
});
复制代码
四:hash和history路由一块儿实现
|----项目demo
| |--- .babelrc # 解决es6语法问题
| |--- node_modules # 全部依赖的包
| |--- dist # 打包后的页面 访问该页面使用:http://0.0.0.0:7799/dist
| |--- js
| | |--- base.js
| | |--- hash.js
| | |--- history.js
| | |--- routerList.js
| | |--- index.js
| |--- package.json # 依赖的包文件
| |--- webpack.config.js # webpack打包文件
| |--- index.html # html 页面
复制代码
index.html 页面以下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hash+history路由demo</title>
</head>
<body>
<div id="app"></div>
<ul class="list">
<li><a href="/">我是主页</a></li>
<li><a href="/hash">我是hash页面</a></li>
<li><a href="/history">我是history页面</a></li>
</ul>
</body>
</html>
复制代码
js/base.js 代码以下:
const ELEMENT = document.querySelector('#app');
export class BaseRouter {
constructor(list) {
this.list = list;
}
render(state) {
let ele = this.list.find(ele => ele.path === state);
ele = ele ? ele : this.list.find(ele => ele.path === '*');
ELEMENT.innerText = ele.component;
}
}
复制代码
如上代码base.js 该类就一个构造函数,在hash.js 或 history.js 会继承该类,所以hash或history类都有该render() 方法。该render方法做用就是找到对应的路径是否等于 routerlist中的path,若是找到的话,就把对应的component里面的内容赋值给 id为app的元素。 js/hash.js 代码以下:
import { BaseRouter } from './base.js';
// hash路由继承了BaseRouter
export class HashRouter extends BaseRouter {
constructor(list) {
super(list);
this.handler();
// 监听hash事件变化,而且从新渲染页面
window.addEventListener('hashchange', (e) => {
this.handler();
});
}
// 渲染
handler() {
const state = this.getState();
this.render(state);
}
// 获取当前的hash
getState() {
const hash = window.location.hash;
return hash ? hash.slice(1) : '/';
}
// 获取完整的url
getUrl(path) {
const href = window.location.href;
const index = href.indexOf('#');
const base = index > -1 ? href.slice(0, index) : href;
return `${base}#${path}`;
}
// hash值改变的话,实现压入
push(path) {
window.location.hash = path;
}
// 替换功能
replace(path) {
window.location.replace(this.getUrl(path));
}
// 模拟history.go 功能,实现前进/后退功能
go(n) {
window.history.go(n);
}
}
复制代码
hash 代码如上;该类里面有hashchange事件监听hash值的变化,若是变化的话就会调用 handler 函数,在执行该函数中的render方法以前,会先调用 getState 方法,该方法目的是获取当前的hash。好比getState方法中使用location.hash 获取的hash会是 '#/x' 这样的,而后会返回 '/x'。 getUrl() 方法是获取完整的url,能够看如上代码理解下便可,其余的就是 push,replace,go方法。
js/history.js 代码以下:
import { BaseRouter } from './base.js';
export class HistoryRouter extends BaseRouter {
constructor(list) {
super(list);
this.handler();
// 监听历史栈变化,变化时候从新渲染页面
window.addEventListener('popstate', (e) => {
this.handler();
});
}
// 渲染
handler() {
const state = this.getState();
this.render(state);
}
// 获取路由路径
getState() {
const path = window.location.pathname;
return path ? path : '/';
}
/*
pushState方法实现压入功能,PushState不会触发popstate事件,
所以咱们须要手动调用handler函数
*/
push(path) {
window.history.pushState(null, null, path);
this.handler();
}
/*
pushState方法实现替换功能,replaceState不会触发popstate事件,
所以咱们须要手动调用handler函数
*/
replace(path) {
window.history.replaceState(null, null, path);
this.handler();
}
go(num) {
window.history.go(num);
}
};
复制代码
代码和hash.js 代码相似。
js/routerList.js 代码以下:
export const ROUTERLIST = [
{
path: '/',
name: 'index',
component: '这是首页'
},
{
path: '/hash',
name: 'hash',
component: '这是hash页面'
},
{
path: '/history',
name: 'history',
component: '这是history页面'
},
{
path: '*',
component: '404页面'
}
];
复制代码
js/index.js 代码以下:
import { HashRouter } from './hash';
import { HistoryRouter } from './history';
import { ROUTERLIST } from './routerList';
// 路由模式,默认为hash
const MODE = 'history';
class WebRouter {
constructor({ mode = 'hash', routerList }) {
this.router = mode === 'hash' ? new HashRouter(routerList) : new HistoryRouter(routerList);
}
push(path) {
// 返回 this.router 所以有 hash或history中的push方法
this.router.push(path);
}
replace(path) {
this.router.replace(path);
}
go(num) {
this.router.go(num);
}
}
const webRouter = new WebRouter({
mode: MODE,
routerList: ROUTERLIST
});
document.querySelector('.list').addEventListener('click', e => {
const event = e || window.event;
event.preventDefault();
if (event.target.tagName === 'A') {
const url = event.target.getAttribute('href');
!url.indexOf('/') ? webRouter.push(url) : webRouter.go(url);
}
});
复制代码
如上就是全部的代码了,仔细研究下看到这样编写代码的好处,就是hash.js,和 history.js 代码分离出来了,而且都有对应的方法,而后在index.js 初始化对应的代码。最后使用dom点击事件传递对应的路由进去。
1.着手写H5代码有一段时间,昨天遇到了一个"神坑"-关于Html中的History对象应用在不一样浏览器效果不一致的问题.
2.问题描述:
1)当调用window.history.go(-1)实现页面返回时,在不一样浏览器上都会真正的从新加载(从新发送网络请求而不是发送网络请求时读取浏览器的缓存)"目标页面"的网络请求.
2)当调用window.history.go(-2)实现返回两级时,在iphone的safari上会"从新加载"(从新发送网络请求但不是真正的发送网络请求而是读取浏览器的缓存),可是须要在返回到"目标网页真正的刷新目标网页.
复制代码
3.解决方法:
1)一开始的思路是记录离开"目标网页" 时的数据,当go(-2)返回到"目标网页"时对数据作相应的加减操做.可是对于复杂的数据类型怎么破.(这种思路用sessionStorage实现的)
2)真正的问题在于再次回到"目标页面"时会读取浏览器缓存,追根溯源,想到了发送网络请求的ajax方法,有没有设置请求不缓存的configuration.结果发现$.ajax(),中有相应的配置选项:cache
当cache为true时会对此次请求以及请求对应的响应进行缓存.为false时不缓存.这样就解决了返回到"目标页面"时读取缓存的问题.
复制代码
4.部分代码展现:
$.ajax({
type: "post",
cache: false,
timeout: 60000,
url: url,
.......复制代码