前端单页面应用路由

单页面应用中,路由由前端控制,前端实现路由主要有两种方式:

  • 一是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);

    }

}

 

转载于:https://www.cnblogs.com/zmiaozzz/p/6605319.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值