路由的基本实现——hash路由
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
问题提出 vue、react在路由的实现上,都有基于hash的路由。那么如何使用原生来实现呢? 比如类似下面这样的路由: hashchange事件是实现路由的核心 hash实现路由的时候,最本质的原理就是hash值的变化,会引发一个hashchange事件,可以根据这个hash值的变化,加载不同的DOM。 html: <div class="box flex-box"> <span class="flex1 center route">home</span> <span class="flex1 center route">shop</span> <span class="flex1 center route">shopcar</span> <span class="flex1 center route">usercenter</span> </div> <div id="root"></div> js: //路由配置 const routes = [{ path:'/0', template:'<div>00000000</div>' },{ path:'/1', template:'<div>11111111</div>' },{ path:'/2', template:'<div>22222222</div>' },{ path:'/3', template:'<div>33333333</div>' }] //基本实现 var mount = document.getElementById('root'); var list = document.getElementsByClassName('route'); for(var i = 0; i < list.length; i++){ list[i].onclick = (function(i){ return function(){ //console.log(window.location,i); window.location.hash=`/${i}`; } })(i) } window.addEventListener('hashchange',function(e){ console.log(e.newURL.split('#')[1]); var path = e.newURL.split('#')[1]; var item = routes.find(function(item){ return item.path == path; }); mount.innerHTML = item.template; }) 完整示例 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <style> .flex-box{ display: flex; } .flex1{ flex: 1; } .center{ display: flex; align-items: center; justify-content: center; } .box{ height: 100px; } .route{ border: 1px solid #ccc; box-sizing: border-box; } </style> </head> <body> <div class="box flex-box"> <span class="flex1 center route">home</span> <span class="flex1 center route">shop</span> <span class="flex1 center route">shopcar</span> <span class="flex1 center route">usercenter</span> </div> <div id="root"></div> </body> <script> const routes = [{ path:'/0', template:'<div>00000000</div>' },{ path:'/1', template:'<div>11111111</div>' },{ path:'/2', template:'<div>22222222</div>' },{ path:'/3', template:'<div>33333333</div>' }] </script> <script> var mount = document.getElementById('root'); var list = document.getElementsByClassName('route'); for(var i = 0; i < list.length; i++){ list[i].onclick = (function(i){ return function(){ //console.log(window.location,i); window.location.hash=`/${i}`; } })(i) } window.addEventListener('hashchange',function(e){ console.log(e.newURL.split('#')[1]); var path = e.newURL.split('#')[1]; var item = routes.find(function(item){ return item.path == path; }); mount.innerHTML = item.template; }) </script> </html> ———————————————— 版权声明:本文为CSDN博主「mapbar_front」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/mapbar_front/article/details/80494623 该文章在 2023/5/30 9:44:27 编辑过 |
关键字查询
相关文章
正在查询... |