一 . 前端路由是什么
- 前端路由主要应用在spa(单页面开发)的项目中。在无刷新的情况下,根据不同的URL来显示不同的组件或内容。
- 前端路由实现的原理:
- hash值 + onhashchange事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>index</button>
<button>list</button>
<h1>Hash模式的前端路由</h1>
<div id="routerView"></div>
<script>
var btn = document.getElementsByTagName('button')
var routerView = document.getElementById('routerView')
var routers = [
{
path: '/index',
component: '<p>我是首页</p>'
},
{
path: '/list',
component: '<p>我是列表页</p>'
}
]
window.location.hash = '/'
btn[0].onclick = function () {
window.location.hash = '/index'
}
btn[1].onclick = function () {
window.location.hash = '/list'
}
window.addEventListener('hashchange', function () {
console.log('hash改变了')
var hash = window.location.hash;
for (var index = 0; index < routers.length; index++) {
if ('#' + routers[index].path == hash) {
routerView.innerHTML = routers[index].component;
}
}
})
// 简单介绍原理,没有做过多的逻辑处理
</script>
</body>
</html>
- history对象 + pushState()方法 + onpopstate事件
history模式注意事项:
* 这种模式需要后台配置支持。因为我们的应用是单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问url时就会返回404,这就不好看了。
* 所以需要在服务端增加一个覆盖所有情况的候选资源:如果RUL匹配不到任何资源,则应该返回同一个index.html页面。所以在测试history时需要在由服务器支持的情况下测试
。话不多说直接上代码--------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>index</button>
<button>list</button>
<h1>History模式的前端路由</h1>
<div id="routerView"></div>
<script>
var btn = document.getElementsByTagName('button')
var routerView = document.getElementById('routerView')
var routers = [
{
path: '/index',
component: '<p>我是首页</p>'
},
{
path: '/list',
component: '<p>我是列表页</p>'
}
]
function render() {
var path = window.location.pathname;
for (var i = 0; i > routers.length; i++) {
if ('router2' + routers[i].path == path) {
routerView.innerHTML = routers[i].component
}
}
}
render()
btn[0].onclick = function () {
history.pushState(routers[0].component, '首页', 'index')
render()
}
btn[1].onclick = function () {
history.pushState(routers[0].component, '列表', 'index')
render()
}
window.addEventListener(popstate, function (ev) {
routerView.innerHTML = ev.state
})
</script>
</body>
</html>
谢谢观看,求关注🙂