How does the front end implement hash routing

Keywords: Javascript Windows IE

Routing Development

Previous routes were implemented by the back end, reloading the page based on the url.However, in recent years, the complexity of front-end pages has led to increased server-side pressure.A natural solution is to change the URL to modify the page content without refreshing the page, which is the front-end routing described in this article.

Routing Classification

Two implementations of front-end routing:

  • Front End Routing Using Hisry Object
  • Listening for hashchange events on Windows objects to implement front-end routing is the hash routing highlighted in this paper

hash routing

What is hash

  • hash is the part of the URL after the'#'character.
  • Changing the hash value does not cause the page to reload.
  • Get and set hash values through the window.location.hash property.

Go directly to the chestnut and explain the hash routing principle through the code.
The effect we want to achieve is to click the left navigation button, switch to the corresponding route, and change the display of the content area.
You can also manually change the routing address, and the content area changes as well.
As shown in the diagram:


One hundred or so lines of code can achieve this simple effect.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>route demo</title>
    <style>
        * {padding: 0;margin: 0;}
        ul li {list-style: none;text-align: center;}
        .main {display: flex;height: 600px;}
        .main .sidebar {width: 200px;border: 2px solid red;}
        .main .sidebar ul {padding-top: 100px;}
        .main .sidebar ul li {margin-bottom: 20px;cursor: pointer; }
        .main .content {flex: 1;border: 2px solid green;padding: 20px;}
    </style>
</head>

<body>
    <div class="main">
        <div class="sidebar">
            <ul class="sidebar-ul">
                <li class="stuManage">Student Management</li>
                <li class="lesManage">course management</li>
                <li class="claManage">Class Management</li>
            </ul>
        </div>
        <div class="content"></div>
    </div>
    <script>
        // Define Route, Route Object Constructor
        function Route(option) {
            this.routes = option.routes;
            this.init();
        }

        // Add Prototype Method to Route
        Route.prototype = {
            constructor: Route,
            // Initialization
            init() {
                // Listen for hashchange events on window objects to get route changes
                window.addEventListener("hashchange", (function (e) {
                    // e.oldURL  e.newURL
                    // Get the changed hash value
                    var hash = location.hash.substring(1);

                    // Match hash to path in locally saved route, match to specified route, execute code for specified module
                    // If no qualifying element is found, the route value is empty
                    var route = this.routes.find(item => {
                        return item.path === hash;
                    }); 
                    if (route) {
                        route.component(hash);
                    }
                }).bind(this));

                // Events are triggered immediately after they are registered, and hashchange events for window s are not triggered after the browser refreshes, so they need to be triggered manually
                var changeEvent = new Event('hashchange');
                window.dispatchEvent(changeEvent);
            },
            // Route Jump
            push({path}) {
                if (path) {
                    location.hash = "#" + path;
                }
            }
        }

        // Switch page display based on route changes
        function changePage(page) {
            var contentDom = document.querySelector('.main .content');
            if (page === '/' || page === '/student') {
                contentDom.innerHTML = 'student module';
            } else if (page === '/lesson') {
                contentDom.innerHTML = 'lesson module';
            } else if (page === '/class') {
                contentDom.innerHTML = 'class module';
            }
        }

        window.onload = function () {
            // Initialize routing configuration by calling constructors, instantiating routing objects
            var router = new Route({
                routes: [
                    { path: "/", component: changePage },
                    { path: "/student", component: changePage },
                    { path: "/lesson", component: changePage },
                    { path: "/class", component: changePage }
                ]
            });

            // Register click events for navigation to switch routes
            document.querySelector('.sidebar-ul').addEventListener("click", function (e) {
                if (e.target.nodeName == "LI") {
                    var domClassName = e.target.className;
                    if (domClassName.indexOf('stuManage') > -1) {
                        router.push({ path: "/student" })
                    } else if (domClassName.indexOf('lesManage') > -1) {
                        router.push({ path: "/lesson" })
                    } else if (domClassName.indexOf('claManage') > -1) {
                        router.push({ path: "/class" })
                    }
                }
            })
        }

    </script>
</body>

</html>

Create a new html file and copy the code to run in the past.You can try to switch routes by clicking the button or by manually entering the route.
Here's a step-by-step explanation of the code.

1. First of all, the core is the Route constructor and the addition of prototype methods to Route.
There are two steps in the Route constructor, 1. Receive parameters.2. Call the init initialization method on the prototype.
Look at the two methods on the prototype.

  • init method: the core of implementing hash routing.The first step in the method is to add monitoring to the hashchange event of the window object, when will the hashchange event be triggered?I have explained above what a hash value is, so when the hash value changes, a hashchange event is triggered, and the event object gets two attributes, oldURL and newURL, representing the url before and after the change, respectively.Of course, you can also get hash values (including #) directly from window.location.hash.Once you get the hash value, all you have to do is iterate through the incoming routing configuration parameters and perform the corresponding operation if there is a matching hash value.
  • push method: A method that provides external calls to jump routes.Change the hash value in the url by passing parameters.

2. Call the Route constructor to instantiate a route object var router = new Route(), and the parameter is our route configuration.The path in the configuration is the changed hash value, and the component is what happens when the hash value is matched, which is the changePage function that we defined above.

3. Calling router.push ({path:'/student'}) when you click the button changes the hash value of the url, triggering the hashchange event for window s and executing our defined changePage function.

summary

This is a simple hash routing implementation. The example is not perfect, but is just a reference for learning principles.Thank you for pointing out any questions.

Posted by jedimaster_att on Tue, 10 Dec 2019 22:49:30 -0800