原生實現hash路由匹配機制

<body>
    <a href="#/">主頁</a>
    <a href="#/index">index</a>
    <a href="#/home">home</a>
    <div id="view"></div>
</body>
<script>
    class Router{
        constructor({routes}) {
            this.routes = routes;
            this.init();
            this.everyPath = {};
            this.routes.forEach(item => {
                this.everyPath[item.path] = function() {
                    document.querySelector('#view').innerHTML = item.component
                }
            })
        }
        init() {
            window.addEventListener('hashchange',this.updateLocation.bind(this))
            window.addEventListener('load',this.updateLocation.bind(this));
        }
        updateLocation() {
            this.everyPath[window.location.hash.slice(1)]()
        }
    }
    new Router({
        routes:[{
            path:'/',
            component:'主頁'
        }, {
            path:'/index',
            component:'index'
        }, {
            path:'/home',
            component:'home'
        }]
    })
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章