如何制作自己的原生JavaScript路由

yizhihongxing

这里为大家详细讲解一下如何制作自己的原生JavaScript路由。

什么是JavaScript路由

JavaScript路由是一种通过JavaScript对页面URL进行控制的技术,它可以实现局部刷新,无需完全刷新页面即可展示新的内容,并且可以通过状态管理实现前端路由系统。

如何制作自己的JavaScript路由

步骤如下:

1. 创建HTML页面

我们以一个简单的单页面应用为例,创建一个HTML页面作为路由的载体。在HTML页面中,我们可以根据自己的需求定义不同的页头、页脚、导航栏等元素。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Router App</title>
</head>
<body>
    <nav>
        <a href="#/">Home</a>
        <a href="#/about">About</a>
        <a href="#/contact">Contact</a>
    </nav>
    <div id="content">
        <h1>Welcome Home!</h1>
        <p>Content will load here...</p>
    </div>
</body>
</html>

2. 实现路由逻辑

为了实现JavaScript路由,我们需要监听window对象的hashchange事件。当URL中的哈希值发生变化时,我们就可以通过自定义的路由规则来决定显示哪个页面。比如我们可以定义一个名为router的函数,来控制路由:

function router() {
    let hash = window.location.hash.substr(1);
    if (hash === "") {
        document.getElementById("content").innerHTML = "<h1>Welcome Home!</h1><p>Content will load here...</p>";
    } else if (hash === "about") {
        document.getElementById("content").innerHTML = "<h1>About Us</h1><p>We are a team of developers...</p>";
    } else if (hash === "contact") {
        document.getElementById("content").innerHTML = "<h1>Contact Us</h1><p>You can send us an email...</p>";
    } else {
        document.getElementById("content").innerHTML = "<h1>Page Not Found</h1><p>The page you requested was not found...</p>";
    }
}

window.addEventListener("hashchange", router);
router();

这个函数的作用是根据不同的哈希值,决定页面显示的内容。在这个示例中,我们根据哈希值的不同,来显示不同的静态页面。

3. 处理路由参数

如果我们想要传递一些参数,比如说我们想让/about页面根据用户不同的参数来动态显示不同的内容,那应该怎么处理呢?

一个常见的方法是在哈希值中使用动态参数,例如#about/:id。这里的id就是参数,我们可以用正则表达式来提取它,然后根据这个参数来显示不同的内容。

function extractParams(template, request) {
    const params = {}; 
    const res = template.exec(request);
    if (res) {
        for (let i = 1; res[i]; i++) {
            params[res[i].split('=')[0]] = res[i].split('=')[1];
        }
    }
    return params;
}

function router() {
    let hash = window.location.hash.substr(1);
    let params = extractParams(/about\/(\w+)/.exec(hash), hash);
    if (hash === "") {
        document.getElementById("content").innerHTML = "<h1>Welcome Home!</h1><p>Content will load here...</p>";
    } else if (hash === "about") {
        if (params && params.id) {
            document.getElementById("content").innerHTML = "<h1>About Us</h1><p>Showing content for user " + params.id + "</p>";
        } else {
            document.getElementById("content").innerHTML = "<h1>About Us</h1><p>We are a team of developers...</p>";
        }
    } else if (hash === "contact") {
        document.getElementById("content").innerHTML = "<h1>Contact Us</h1><p>You can send us an email...</p>";
    } else {
        document.getElementById("content").innerHTML = "<h1>Page Not Found</h1><p>The page you requested was not found...</p>";
    }
}

window.addEventListener("hashchange", router);
router();

在这个示例中,我们定义了一个extractParams函数,用于提取哈希值中的参数。然后在router函数中,我们根据提取到的参数来动态显示不同的内容。

示例

以上是制作自己的JavaScript路由的具体过程,下面我为大家提供两个适用示例。

1. 基本的SPA应用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Router App</title>
</head>
<body>
    <nav>
        <a href="#/">Home</a>
        <a href="#/about">About</a>
        <a href="#/contact">Contact</a>
    </nav>
    <div id="content">
        <h1>Welcome Home!</h1>
        <p>Content will load here...</p>
    </div>
    <script>
        function router() {
            let hash = window.location.hash.substr(1);
            if (hash === "") {
                document.getElementById("content").innerHTML = "<h1>Welcome Home!</h1><p>Content will load here...</p>";
            } else if (hash === "about") {
                document.getElementById("content").innerHTML = "<h1>About Us</h1><p>We are a team of developers...</p>";
            } else if (hash === "contact") {
                document.getElementById("content").innerHTML = "<h1>Contact Us</h1><p>You can send us an email...</p>";
            } else {
                document.getElementById("content").innerHTML = "<h1>Page Not Found</h1><p>The page you requested was not found...</p>";
            }
        }

        window.addEventListener("hashchange", router);
        router();
    </script>
</body>
</html>

2. 处理动态路由参数的应用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Router App</title>
</head>
<body>
    <nav>
        <a href="#/">Home</a>
        <a href="#/about">About</a>
        <a href="#/about/123456">About User #123456</a>
        <a href="#/contact">Contact</a>
    </nav>
    <div id="content">
        <h1>Welcome Home!</h1>
        <p>Content will load here...</p>
    </div>
    <script>
        function extractParams(template, request) {
            const params = {}; 
            const res = template.exec(request);
            if (res) {
                for (let i = 1; res[i]; i++) {
                    params[res[i].split('=')[0]] = res[i].split('=')[1];
                }
            }
            return params;
        }

        function router() {
            let hash = window.location.hash.substr(1);
            let params = extractParams(/about\/(\w+)/.exec(hash), hash);
            if (hash === "") {
                document.getElementById("content").innerHTML = "<h1>Welcome Home!</h1><p>Content will load here...</p>";
            } else if (hash === "about") {
                if (params && params.id) {
                    document.getElementById("content").innerHTML = "<h1>About Us</h1><p>Showing content for user " + params.id + "</p>";
                } else {
                    document.getElementById("content").innerHTML = "<h1>About Us</h1><p>We are a team of developers...</p>";
                }
            } else if (hash === "contact") {
                document.getElementById("content").innerHTML = "<h1>Contact Us</h1><p>You can send us an email...</p>";
            } else {
                document.getElementById("content").innerHTML = "<h1>Page Not Found</h1><p>The page you requested was not found...</p>";
            }
        }

        window.addEventListener("hashchange", router);
        router();
    </script>
</body>
</html>

以上就是制作自己的JavaScript路由的完整攻略,希望对大家有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:如何制作自己的原生JavaScript路由 - Python技术站

(0)
上一篇 2023年6月11日
下一篇 2023年6月11日

相关文章

  • JavaScript 浏览器兼容性总结及常用浏览器兼容性分析

    JavaScript 浏览器兼容性总结及常用浏览器兼容性分析 什么是浏览器兼容性? 浏览器兼容性指的是不同的浏览器(如 Chrome、Safari、Firefox、Edge 等)在对同一段代码的解释和运行方式上存在差异的情况。 由于各个浏览器采取的内核和标准不同,所以同一段 JavaScript 代码在不同的浏览器上的表现可能完全不同。因此,在开发网站或应用…

    JavaScript 2023年6月10日
    00
  • JavaScript reduce的基本用法详解

    JavaScript reduce的基本用法详解 reduce() 方法通过指定函数对数组元素进行累积计算,可将数组简化为单个值。它接收一个回调函数作为参数,该回调函数需要返回一个累积的结果。 基本语法 array.reduce(function(total, currentValue, currentIndex, arr), initialValue) 参…

    JavaScript 2023年5月18日
    00
  • JavaScript window.document的属性、方法和事件小结

    那么让我们来详细讲解“JavaScript window.document的属性、方法和事件小结”的攻略。 文档对象模型(DOM) 首先,我们需要了解文档对象模型(DOM),这是一种针对HTML和XML文档的面向对象编程接口,我们可以通过DOM操作HTML文档的元素、属性和样式等。在JavaScript中,DOM是非常重要的一个概念,也是JavaScript…

    JavaScript 2023年6月10日
    00
  • js跨域请求数据的3种常用的方法

    下面是详细讲解”js跨域请求数据的3种常用的方法”的攻略: 1. 跨域请求数据的背景 在Web开发的过程中,经常会遇到需要通过js代码来请求数据的情况。我们知道,由于同源策略(Same-origin policy)的限制,不同源(域)之间的js代码请求是受限制的。跨域请求数据就是在解决这个限制的前提下来实现的。 2. 跨域请求数据的3种常用的方法 2.1 J…

    JavaScript 2023年5月27日
    00
  • JavaScript ES6 Class类实现原理详解

    下面是关于JavaScript ES6 Class类实现原理的详细攻略。 什么是ES6 Class ES6引入了Class关键字,通过它可以使用类的方式来编写JavaScript代码,使得代码更加可读性强,易于维护和重构。 一个基础的ES6类的定义方式如下: class Person { constructor(name, age) { this.name …

    JavaScript 2023年5月28日
    00
  • 20行js代码实现的贪吃蛇小游戏

    20行js代码实现的贪吃蛇小游戏攻略 1. 实现思路 该贪吃蛇小游戏的实现思路非常简单,主要分为以下两步: 初始化游戏BOSS。 在游戏中添加监听事件,监听玩家的操作,并处理游戏逻辑。 2. 代码实现 游戏的实现代码如下: with(document){ a = appendChild(createElement("canvas")).g…

    JavaScript 2023年5月27日
    00
  • JavaScript中String对象的方法介绍

    下面是 JavaScript 中 String 对象的方法介绍: 1. String 对象简介 String 对象是 JavaScript 中用于表示文本字符串的标准对象。通过 String 对象的属性和方法,我们可以方便地获取字符串的长度、查找子字符串、替换子字符串等。 2. String 对象常用方法介绍 2.1 charAt() 方法 charAt()…

    JavaScript 2023年5月27日
    00
  • Javascript Math min() 方法

    JavaScript中的Math.min()方法是用于返回一组数中的最小值的函数。以下是关于Math.min()方法的完整攻略,包含两个示例。 JavaScript Math对象的min()方法 JavaScript Math的min()方法用于返回一数中的最小。下面是min()方法的语法: Math.min([value1[,2 …]]]) 其中,va…

    JavaScript 2023年5月11日
    00
合作推广
合作推广
分享本页
返回顶部