前端單頁面應用路由

單頁面應用中,路由由前端控制,前端實現路由主要有兩種方式:html

  • 一是HTML5推出的history API,由pushState()記錄操做歷史,監聽popstate事件來進行視圖切換;
  • 二是使用hash值,經過監聽hashchange事件來進行視圖切換

 

如下是一個路由示例:前端

<div id="route">
    <a href="#/page1">page1</a>
    <a href="#/page2">page2</a>
    <a href="#/page3">page3</a>
</div>

<div id="content"></div>
var util = {
    history: !!window.history && window.history.pushState,
    hashchange: 'onhashchange' in window
}

window.onload = function () {
    var router = new Router();


   // 路由配置
    router.when('/page1', {
        template: '<h1>page1</h1>'
    }).when('/page2', {
        template: '<h1>page2</h1>'
    }).when('/page3', {
        template: '<h1>page3</h1>'
    }).otherwise('/page1')

    router.fireUrlChange();


    if(util.history) {
        // 頁面地址改變,更新頁面
        $(window).on('popstate', function () {
            router.fireUrlChange();
        })
    }

    if(util.hashchange) {
        // hash值改變時更新頁面
        $(window).on('hashchange', function () {
            router.fireUrlChange();
        });
    }


}


function Router() {
    this.routers = {};
}
Router.prototype = {
    constructor: Router,

    /**
     * 添加路由
     * @param path
     * @param route
     * @returns {Router}
     */
    when: function (path, route) {
        this.routers[path] = route;

        return this;
    },

    /**
     * 首次加載路由
     * @param url
     */
    otherwise: function (url) {
        this.newUrl = url;
    },

    /**
     * 路由改變時觸發
     */
    fireUrlChange: function () {

        // 首次加載otherwise路由
        if(!location.hash) {
            if(util.history) {
                history.pushState(null, '', location.href+'#'+this.newUrl);
            }
            if(util.hashchange) {
                location.hash = this.newUrl;
            }

        }

        this.newUrl = location.hash.substring(1);

        // 路由沒有變化
        if(this.newUrl === this.lastUrl) {
            return;
        }

        // 路由發生變化
        this.lastUrl = this.newUrl;


        //更新頁面
        var $content = $('#content');
        $content.html(this.routers[this.newUrl].template);

    }

}
相關文章
相關標籤/搜索