原生實現history路由匹配機制

<body>
    <a href="javascript:;" data-to='/'>首頁</a>//跳空
    <a href="javascript:;" data-to='/home'>home</a>
    <a href="javascript:;" data-to='/index'>index</a>
    <div id="view"></div>
</body>
<script>
    class Router {
        constructor({routes}) {
            this.routes = routes;
            this.bindClick();
            this.init()
        }
        init() {
            window.addEventListener('popstate', this.updataView.bind(this))
        }
        bindClick() {
            let pushA = document.querySelectorAll('a');
            [].forEach.call(pushA, item => {
                item.addEventListener('click',() => {
                    let clickRes = item.getAttribute('data-to');
                    window.history.pushState({},null,clickRes);
                    this.updataView()
                })
            })
        }
        updataView() {
            view.innerHTML = this.routes.filter(item => item.path === window.location.pathname)[0].component
        }
    }
    new Router({
        routes:[
            {
                path:'/',
                component:'首頁'
            },
            {
                path:'/home',
                component:'home'
            },
            {
                path:'/index',
                component:'index'
            }
        ]
    })
</script>

注意:history要起靜態服務,否則會報錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章