Vue: routing principle (hash)

Code directly

  • Write something on the page
<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>
  • The first one is displayed by default, which is the homepage
<style>
  #about {
     
     
    display: none;
  }
  #info {
     
     
    display: none;
  }
</style>
  • Take a look at the page effect
  • Now you need to achieve the requirements, clickonThe page shows about and at the same timeURLAlso display the corresponding a taghrefContent

Insert picture description here

  • byhashchangeChange events to fulfill this requirement
  • hashIs the URL displayed on the page
  • A lotifJudgment is to let the corresponding text display
  • Document.getElementById is not used because it can be used directly when the element is the only element on the page
  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';
    }
  } 
  • Take a look at the printedhash

Insert picture description here

  • Take a look at the page effect

Insert picture description here

Vue routing jump (positive play)

  • Does it feel familiar?
  • This is how vue is configured for routing
  • pathIs displayed in the address barURL
  • componentNeed to be displayedpage, Here are those divs
const router = [
  {
    
    path:'#/home',component:home},
  {
    
    path:'#/about',component:about},
  {
    
    path:'#/info',component:info}
]
  • The corresponding js code
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; //匹配到之后跳出循环,提高性能
    }
  }
}
  • See if the effect is the same

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_47883103/article/details/108400067