如何通过前端路由技术实现单页应用(SPA)?

如何通过前端路由技术实现单页应用(SPA)?

阅读 469
1 个回答

这个简单的路由类通过 pushStatepopstate 事件来实现前端路由。

示例代码**:

class Router {
    constructor() {
        this.routes = {};
        window.addEventListener('popstate', this.handlePopState.bind(this));
    }

    addRoute(path, callback) {
        this.routes[path] = callback;
    }

    navigate(path) {
        history.pushState({}, '', path);
        this.handlePopState();
    }

    handlePopState() {
        const path = window.location.pathname;
        if (this.routes[path]) {
            this.routes[path]();
        }
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题