8Vue-Router - 前端路由实现思路

129 阅读1分钟

8.1 目录

8.2 路由是什么

路由就是分发请求
路由器就是 分发请求的机器.

8.3 优化代码

index.html

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>router</title>
</head>
<body>
    <a href="#1">go to 1</a>
    <a href="#2">go to 2</a>
    <a href="#3">go to 3</a>
    <a href="#4">go to 4</a>
    <div id="app"></div>

    <div id="div1" style="display: none">1</div>
    <div id="div2" style="display: none">2</div>
    <div id="div3" style="display: none">3</div>
    <div id="div4" style="display: none">4</div>
    <div id="div404" style="display: none">404</div>

    <script src="./src/index.js"></script>
</body>
</html>

index.js

function route(){
    //获取用户想去哪
    let number = window.location.hash.substr(1) || 1
    let app = document.querySelector("#app")
    //获取界面
    let div = document.querySelector(`#div${number}`)
    if(!div){
        div = document.querySelector("#div404")
    }
    //渲染界面
    div.style.display = "block"
    if(app.children.length > 0){
        app.children[0].style.display = "none"
        document.body.appendChild(app.children[0])
    }
    //展示界面
    app.appendChild(div)
}
route()

//检测hash改变
window.addEventListener("hashchange", ()=>{
    console.log("路由改变了");
    route()
})

8.4 路由表

index.html

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>router</title>
</head>
<body>
    <a href="#1">go to 1</a>
    <a href="#2">go to 2</a>
    <a href="#3">go to 3</a>
    <a href="#4">go to 4</a>
    <div id="app"></div>
    <div id="div404" style="display: none">404</div>

    <script src="./src/index.js"></script>
</body>
</html>

index.js

const div1 = document.createElement("div")
div1.innerHTML = "1"
const div2 = document.createElement("div")
div2.innerHTML = "2"
const div3 = document.createElement("div")
div3.innerHTML = "3"
const div4 = document.createElement("div")
div4.innerHTML = "4"
const routeTable = {
    "1": div1,
    "2": div2,
    "3": div3,
    "4": div4
}

function route(){
    //获取用户想去哪
    let number = window.location.hash.substr(1) || 1
    let app = document.querySelector("#app")
    //获取界面
    let div = routeTable[number.toString()]
    if(!div){
        div = document.querySelector("#div404")
    }
    //渲染界面
    div.style.display = "block"

    //展示界面
    app.innerHTML = ""
    app.appendChild(div)
}
route()

//检测hash改变
window.addEventListener("hashchange", ()=>{
    console.log("路由改变了");
    route()
})

8.5 history模式

hashbang 谷歌针对hash路由问题的方案

8.6 history和hash模式的对比

image.png

8.7 memory模式

image.png

8.8 如何阅读VueRouter源代码