原生JS简单实现前端路由(即监听URL改变并操作)

封装为函数的版本:监听 & 刷新

function refresh() {
    var req = location.hash.slice(1) || '/';
    console.log(req); //此处可替换为URL操作方法
}

function bind_uri_refresh() {
    window.addEventListener('load', refresh.bind(this), false);
    window.addEventListener('hashchange', refresh.bind(this), false);
}

bind_uri_refresh();

封装为类的版本:封装监听事件

function Router() {
}
Router.prototype.refresh = function() {
    console.log(location.hash.slice(1));//获取到相应的hash值
    this.currentUrl = location.hash.slice(1) || '/';//如果存在hash值则获取到,否则设置hash值为/
};
Router.prototype.init = function() {
    window.addEventListener('load', this.refresh.bind(this), false);
    window.addEventListener('hashchange', this.refresh.bind(this), false);
}
//给window对象挂载属性
window.Router = new Router();
window.Router.init();

增加回调功能的版本:将URI映射为对应的函数
完整代码来源于原生JS实现一个简单的前端路由(路由实现的原理)

function Router() {
    this.routes = {};
    this.currentUrl = '';
}
Router.prototype.route = function(path, callback) {
    this.routes[path] = callback || function(){};//给不同的hash设置不同的回调函数
};
Router.prototype.refresh = function() {
    console.log(location.hash.slice(1));//获取到相应的hash值
    this.currentUrl = location.hash.slice(1) || '/';//如果存在hash值则获取到,否则设置hash值为/
    // console.log(this.currentUrl);
    this.routes[this.currentUrl]();//根据当前的hash值来调用相对应的回调函数
};
Router.prototype.init = function() {
    window.addEventListener('load', this.refresh.bind(this), false);
    window.addEventListener('hashchange', this.refresh.bind(this), false);
}
//给window对象挂载属性
window.Router = new Router();
window.Router.init();

Router.route('/', function() {
    console.log("test");
});
Router.route('/1', function() {
    console.log("aaa");
});
Router.route('/2', function() {
    console.log("bbb");
});

猜你喜欢

转载自blog.csdn.net/dreamstone_xiaoqw/article/details/80924082
今日推荐