Vue:路由原理(hash)

tech2025-08-01  14

直接上代码

在页面上写点东西 <p><a href="#/home">首页</a>|<a href="#/about">关于</a>|<a href="#/info">信息</a></p> <div id="home"> <h1>首页</h1> </div> <div id="about"> <h1>关于</h1> </div> <div id="info"> <h1>信息</h1> </div> 默认显示第一个,也就是首页 <style> #about { display: none; } #info { display: none; } </style> 看一下页面效果现在需要实现需求,点击关于页面显示关于,同时URL也显示对应的a标签href的内容

通过hashchange改变事件来实现这个需求hash就是页面上显示URL一大堆if判断就是让对应的文字显示没有用document.getElementById是因为,当元素为页面唯一元素的时候可以直接用 window.onhashchange = function (e) { let hash = window.location.hash; console.log(hash) // 打印出来hash看一下 if (hash == '#/home') { home.style.display = 'block'; about.style.display = 'none'; info.style.display = 'none'; } else if (hash == '#/about') { home.style.display = 'none'; about.style.display = 'block'; info.style.display = 'none'; } else if (hash == '#/info') { home.style.display = 'none'; about.style.display = 'none'; info.style.display = 'block'; } } 看一下打印出来的hash

看一下页面效果

Vue路由跳转(正戏)

是不是感觉很熟悉?这就是vue的路由配置方式path是地址栏显示的URLcomponent是需要显示对用的页面,在这里就是那几个div const router = [ {path:'#/home',component:home}, {path:'#/about',component:about}, {path:'#/info',component:info} ] 对应的js代码 let currentView = router[0]; // 默认显示第一个页面 window.onhashchange = function(e) { for(let i = 0; i < router.length; i++) { if(location.hash == router[i].path) { // 如果URL匹配到 currentView.component.style.display = 'none'; // 关闭默认显示的页面 router[i].component.style.display = 'block'; // 显示匹配到的页面 currentView = router[i]; // 更改默认显示的页面为当前页面 break; //匹配到之后跳出循环,提高性能 } } } 看一下效果是否一样

最新回复(0)