Vue:路由原理(hash)

直接上代码

  • 在页面上写点东西
<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是地址栏显示的URL
  • component是需要显示对用的页面,在这里就是那几个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; //匹配到之后跳出循环,提高性能
    }
  }
}
  • 看一下效果是否一样

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_47883103/article/details/108400067