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

1.路由是什么?

Router路由器: 数据包转发设备,路由器通过转发数据包(数据分组)来实现网络互连

**Route路由:**数据分组从源到目的地时,决定端到端路径的网络范围的进程 | - 网络层

**Distribute分发:**数据包或任务根据规则,分配到不同的路径

Default Route 默认路由: 路由表中没有匹配的路由时,默认显示的路由

Fallback Routing404路由/保底路由: 匹配所有处理未定义或未找到路由请求的特殊路由

Nested Routing 嵌套路由: 一个路由组件内部定义其他路由组件,形成父子结构的路由

Routing Table **路由表:**存储到各个目的地的最佳路径的表,引导分组转送 | - 对象

html 复制代码
#原生js实现路由

/* index.html */
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test Router</title>

</head>
<body>
  <section>
     <a href="#1">page 1</a><br/>
     <a href="#2">page 2</a><br/>
     <a href="#3">page 3</a><br/>
     <a href="#4">page 4</a><br/>
  </section>

  <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">
      <span>404</span><hr/><span>Not found</span>
  </div>

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

<style>
    a{
       color: blueviolet;
       text-decoration: none;
    }
    #app{
        background: pink;
        font-size: 32px;
    }
    #div404{
        text-align: center;
    }
</style>
javascript 复制代码
/* main.js 实现不同路由匹配不同页面 */

function route(){
    /* 获取hash */
    let hash=window.location.hash
    let number=hash.substr(1) || '1'
    console.log(hash,number)

    /* 获取并显示当前哈希匹配的div */
    let div=document.querySelector(`#div${number}`)
    if (div) {
        div.style.display = "block";
        let app = document.querySelector('#app');
        app.appendChild(div);
    }else{
        /* 保底路由404 */
        div = document.querySelector(`#div404`)
        div.style.display = "block";
        document.querySelector("body").appendChild(div);
    }
}
route()

window.addEventListener("hashchange",()=>{
    /* 隐藏所有div */
    let allDivs = document.querySelectorAll('[id^="div"]');
    allDivs.forEach(div => div.style.display = "none");

    /* 更新路由匹配 */
    route()
})

2.路由的三种模式

相关推荐
q***12533 分钟前
Plugin ‘org.springframework.bootspring-boot-maven-plugin‘ not found(已解决)
java·前端·maven
攻城狮CSU4 分钟前
C# 异步方法
开发语言·前端·c#
tyro曹仓舒5 分钟前
干了10年前端,才学会使用IntersectionObserver
前端·javascript
S***y39626 分钟前
前端微前端框架对比,qiankun与icestark
前端·前端框架
Wect36 分钟前
学习React-DnD:实现多任务项拖拽-useDrop处理
前端·react.js
Mintopia1 小时前
Trae Coding - 「Excel 秒变海报」—— 上传 CSV,一句话生成可打印信息图。
前端·人工智能·trae
晴殇i1 小时前
CSS 相对颜色:告别 180 个颜色变量的设计系统噩梦
前端·css
MegatronKing1 小时前
Reqable 3.0版本云同步的实践过程
前端·后端·测试
李剑一1 小时前
我用Trae生成了一个Echarts 3D柱状图的Demo
前端·vue.js·trae
Crystal3281 小时前
3D实战案例(飞行的火箭/创建3D导航/翻书效果/创建长方体/环环相扣效果)
前端·css