代码升级(组件化开发)
index.html
<div id="box"> <div class="top">顶部通栏</div> <div class="bottom"> <div class="slide"> <a href="#/first">first</a> <a href="#/second">second</a> <a href="#/third">third</a> <a href="#/fourth">fourth</a> </div> <div class="content router-view"></div> </div> </div>
*{ margin: 0; padding: 0; } html,body,#box{ width: 100%; height:100%; } #box{ display: flex; flex-direction:column; } #box>.top{ height: 130px; background: skyblue; } #box>.bottom{ flex:1; display: flex; } #box>.bottom>.slide{ width: 230px; background-color: orange; box-sizing: border-box; padding: 15px; } #box>.bottom>.slide>a{ font-size: 22px; display: block; margin: 10px 0; text-decoration: none; color: #333; } #box>.bottom>.content{ flex: 1; box-sizing: border-box; padding: 15px; background: purple; font-size: 100px; color: white }
<script src="./index.js" type="module"></script>
components 组件
first.js
//组件的html结构 const template = ` <div id="first"> first </div> `; //获取到路由出口对象 const routerView = document.querySelector('.router-view'); //准备一个渲染函数 function render(){ routerView.innerHTML = template; } //导出渲染函数 export default render;
second.js
//组件的html结构 const template = ` <div id="second"> second </div> `; //获取到路由出口对象 const routerView = document.querySelector('.router-view'); //准备一个渲染函数 function render(){ routerView.innerHTML = template; } //导出渲染函数 export default render;
third.js
//组件的html结构 const template = ` <div id="third"> third </div> `; //获取到路由出口对象 const routerView = document.querySelector('.router-view'); //准备一个渲染函数 function render(){ routerView.innerHTML = template; } //导出渲染函数 export default render;
fourth.js
//组件的html结构 const template = ` <div id="fourth"> fourth </div> `; //获取到路由出口对象 const routerView = document.querySelector('.router-view'); //准备一个渲染函数 function render(){ routerView.innerHTML = template; } //导出渲染函数 export default render;
router.js
//导入组件模块 import firstCom from './components/first.js'; import secondCom from './components/second.js'; import thirdCom from './components/third.js'; import fourthCom from './components/fourth.js'; // 定义路由表 const router = [ { name : '/first', component: firstCom }, { name: '/second', component: secondCom }, { name: '/third', component: thirdCom }, { name: '/fourth', component: fourthCom } ]; //导出路由 export default router;
index.js
//1. 导入路由表 import router from './router.js'; //2. 注册hashchange 事件 window.onhashchange = hashChange; hashChange(); //3. 处理程序 function hashChange(){ console.log('根据当前hash值,进行改变'); //获取当前的hash值 const hash = window.location.hash.slice(1) || '/'; // console.log(hash); //从路由表中找到hash对应的那一个信息 const info = router.find(item => item.name === hash); console.log(info); //如果没有内容,不需要后续操作 if(!info){ return; } //渲染页面 info.component(); }