方君の小窝 方君の小窝
首页
  • 原生js总结
  • 样式相关
  • vue
  • 其他必备知识
  • php
其他
GitHub

方君

迷糊小前端
首页
  • 原生js总结
  • 样式相关
  • vue
  • 其他必备知识
  • php
其他
GitHub
  • 原生js总结

  • 样式相关

  • vue

    • vue基础
    • vue自定义指令&生命周期
    • vue组件
    • vue组件传值
    • vue路由
    • 路由机制
      • 原生router/hash版
      • 原生router/history版
      • 总结
  • 其他必备知识

  • 前端
  • vue
方君
2020-08-24

vue路由机制

前端路由:在应用使用期间不会重新加载,提高用户体验,减低网速要求,界面展开快。前后端分离方便开发

目前前端路由有两种实现方法:

  1. 利用url的hash,当浏览器url的锚点部分发生改变,不会刷新页面的原理
  2. 利用h5中的history,通过监听opostate事件,利用pushstate或replacestate实现

# 原生router/hash版

html:

<ul>
    <li><a href="#/home">home</a></li>
    <li><a href="#/about">about</a></li>
</ul>

<div id="routerView"></div>
1
2
3
4
5
6

js:

var routerView=document.querySelector("#routerView");
window.addEventListener("DOMContentLoaded",onchange);
window.addEventListener("hashchange",onchange);

function onchange(){
    switch(location.hash){
        case "#/home":
            routerView.innerHTML="home";
            return;
        case "#/about":
            routerView.innerHTML="about";
            return;
        default:
            routerView.innerHTML="";
            return;
           }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 原生router/history版

html:

<ul>
    <li><a href="/home">home</a></li>
    <li><a href="/about">about</a></li>
</ul>

<div id="routerView"></div>
1
2
3
4
5
6

js:

var routerView=document.querySelector("#routerView");

window.addEventListener("popstate",onchange);    
//调用push,replace不会触发popstate事件,但是浏览器操作可以触发

document.querySelectorAll("a[href]").forEach(
    	el=> el.addEventListener("click",function(e){
    	e.preventDefault();                  //阻止A标签默认行为
    	var path=el.getAttribute("href");
    	history.pushState(null,"",path);     //@param 1)状态对象2)标题3)URL
        onchange();                          //手动触发
}))
function onchange(){
    switch(location.pathname){
        case "/home":
            routerView.innerHTML="home";
            return;
        case "/about":
            routerView.innerHTML="about";
            return;
        default:
            routerView.innerHTML="";
            return;
           }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 总结

hash:

  1. 利用锚点导航(改变URL中的hash不引起页面刷新)
  2. hashchange监听hash变化,(浏览器前后退,a标签,window.location均可触发)

history:

  1. history对象提供了pushState和replaceState方法,这两个方法改变URL不会引起页面刷新
  2. popstate事件,(浏览器前后退可触发,a标签需阻止默认,window.location需改写成history.pushState)
编辑
#基础
vue路由
gulp

← vue路由 gulp →

最近更新
01
vue自定义指令&生命周期
08-24
02
ajax
08-24
03
promise
08-24
更多文章>
Theme by Vdoing | Copyright © 2019-2020
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式