We can implement front-end routing using hash and H5 history. We only implement the core part of the route. We do not consider error handling, parameter passing, etc.

HTML code <a class="a" href=""> here is a</a> <a class="b" href=""> here is b</a> <a class="c" href=""> here is c</a> <div class="box"></div>
Copy the code

CSS code a {width: 200px; height: 50px;float: left;
}

.box {
    width: 100%;
    height: 500px;
    background-color: pink;
    overflow: hidden;
}Copy the code

Hash

The hash method is to artificially add a # to a page when we click on a link to jump to, so that the browser will not jump to the page. I personally don’t like to add a # to the page, so I use the click event to dynamically add:

let body = document.querySelector('body')

body.addEventListener('click'.function (e) {
    e.target.attributes.href.value = `#${e.target.className}`
})Copy the code

I used the name of the class to distinguish the different paths (it’s better to just add a # ~). Now we implement a method to change the color of the red box below by clicking on the different A tags as follows:

Class Router {// Route to implement the switch function path (path) corresponding to the callback function (cb)constructor// Save the current path this.currenturl =' 'This.routes = {} // If this is added to the window, it will cause an error. We will bind this to add listening events to the router instance this.update = this.update.bind(this) // window object when loading (user refreshes page) andhashThe window.addeventListener () callback is called when the value changes (user jumps).'load', this.update)
        window.addEventListener('hashchange', this.update)
    }
    update() {// Get the current pageThe value after #, if there is no hash, defaults to the home page
        this.currentUrl = location.hash.split(The '#') [1] | |' 'This.routes [this.currenturl]()} this.routes[this.currenturl]()}Copy the code

Maybe some friends don’t understand this:

Update = this.update. Bind (this)Copy the code

If you print this in the update method, an error will be reported because the addEventListener binds this to the window, which has no update method

So we’ve got a little route, a little demo test,

const router = new Router()
router.save(' '.function() {
    box.style.backgroundColor = 'red'
})
router.save('a'.function() {
    box.style.backgroundColor = 'red'
})
router.save('b'.function() {
    box.style.backgroundColor = 'blue'
})
router.save('c'.function() {
    box.style.backgroundColor = 'yellow'
})Copy the code

As far as the history API goes, sometimes the popState event e.state will be null…