路由的基本實現——hash路由
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
問題提出 vue、react在路由的實現上,都有基于hash的路由。那么如何使用原生來實現呢? 比如類似下面這樣的路由: hashchange事件是實現路由的核心 hash實現路由的時候,最本質的原理就是hash值的變化,會引發(fā)一個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」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權協(xié)議,轉載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/mapbar_front/article/details/80494623 該文章在 2023/5/30 9:44:27 編輯過 |
關鍵字查詢
相關文章
正在查詢... |