- 路由是什么?
- hash模式,history模式,memory模式
路由是什么
路由:分发请求
这个东西就是路由器
什么是路由:分发请求的东西
学习路由要从基础的学起,每个框架的路由的原理都一样,只是代码不一样,所以只要把原理搞清楚了,学起来就很快。
根据用户的url不同,展示不同的页面
hash
可以通过window.location.hash
可以得到url
后面的#n
(n是1,2,3…数字)
const number = window.location.hash.substr(1)
就得到#
后面的数字
然后通过
const div = document.querySelector(`#div${number}`);
可以得到这个div标签
const app = document.querySelector("#app");
div.style.display = "block"
,最开始设置的是隐藏,现在改成显示
app.appendChild(div);
查入到节点中
const number = window.location.hash.substr(1);
const div = document.querySelector(`#div${number}`);
const app = document.querySelector("#app");
div.style.display = "block;
app.appendChild(div);
<a href="#1">go to 1</a>
,在页面展示给用户点击,去那个地方,用户点击,然后URL被改变,但是上面的渲染部分只有在最开始的时候才执行,所以要去搜一下hash change mdn
hash:上面的(#1)
默认路由:404路由/保底路由
<div id="div404" style="display: none;">404,页面找不到</div>
js中写
let div = document.querySelector(`#div${number}`);
if(div){
div.style.display = "block";
}else {
div = document.querySelector('#div404');
div.style.display = "block";//展示出来
}//找不到对应的路由,就用这个默认的404路由
根据你想去的地方(number),获取页面(div)展示给你(渲染)
优化后的代码
function router() {
let number = window.location.hash.substr(1);
let app = document.querySelector("#app");
number = number || 1;
//获取界面
let div = document.querySelector(`#div${number}`);
if(!div) {
div = document.querySelector("#div404");
}
div.style.display = "block";
//展示页面
if(app.children.length>0) {
app.children[0].style.display = "none";
document.body.appendChild(app.children[0]);
}
app.appendChild(div);
}
route();
window.addEventListener("hashchange", () => {
console.log("hash 变了");
route();
});
路由表
上面的hash和div的对应关系,不太好,用一个路由表就好了。
const div1 = document.createElement('div')
div.innerHTML = '1'
const div2 = document.createElement('div')
div.innerHTML = '2'
const div3 = document.createElement('div')
div.innerHTML = '3'
const div4 = document.createElement('div')
div.innerHTML = '4'
const routeTable = {
'1': div1,
'2': div2,
'3': div3,
'4': div4
}
这也叫表驱动编程
嵌套路由
这个时候就会有好几个个路由表了,分别对应第几层
例如两层[1,1]就是#1/1
,就会有两层路由表来处理两个1
hash/history/memory三个的区别
hash:
- 任何情况下都能做前端路由
- seo不友好(服务器收不到hash,浏览器不会吧#之后的内容发给服务器)
history: - 后端将所有前端路由都渲染到同一个页面(同一个页面不能是404),不管输入什么,都到你的首页
- IE8一下不支持
memory: - URL永远不变
- 存到localstorage里面
hash通过hash得到number从/#1
里let number = window.location.hash.substr(1);
history通过pathname得到number从/1
里let number = window.location.pathname;
使用history模式就要阻止a
标签的跳转
然后使用history的API
const href = a.getAttribute("href");//href就是url后面的/1跳转的地址
window.history.pushState(null, `page ${href}`,href);//改url不刷新页面
onStateChange(href);//重新路由一下
function onStateChange(href) {
route(app);
}
history为什么需要所有页面都指向同一个页面呢,因为用户喜欢刷新
memory:
let number = window.localStorage.getItem('xxx')
把所有路由信息存到xxx中,从localStorage中获取
const href = a.getAttribute("href");
window.localStorage.setItem('xxx', href);//存到localStorage里
onStateChange(href);
memory
适合非浏览器,单机版路由(分享链接出去,两个人得到页面的不一样)