Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
<h1>Router Navigation Example</h1>  
<button id="home-btn">首页</button>  
<button id="about-btn">关于</button>  
<button id="not-found-btn">404页面</button> 
              
            
!

CSS

              
                
              
            
!

JS

              
                class Router {  
    routes = {  
        '/': { render: () => console.log('首页') },  
        '/about': { render: () => console.log('关于') },  
        '/404': { render: () => console.log('404页面未找到') }  
    };  
    currentUrl = '';  
    beforeHooks = [];  
    afterHooks = [];  
    mode = 'history';  
  
    constructor({ mode = 'history', routes, currentUrl = '/' } = {}) {  
        this.mode = mode;  
        if (routes) this.routes = routes;  
        this.currentUrl = currentUrl;  
        this.init();  
    }  
  
    init() {  
        if (this.mode === 'history') {  
            window.addEventListener('popstate', () => this.routeChanged());  
        } else if (this.mode === 'hash') {  
            window.addEventListener('hashchange', () => this.routeChanged());  
        }  
        this.routeChanged(); // 处理初始路由  
    }  
  
    async routeChanged() {  
        const path = this.getCurrentPath();  
        await this.handleRouteChange(path);  
    }  
  
    async handleRouteChange(path) {  
        const from = this.currentUrl;  
        const to = path;  
  
        console.log("from", from)  
        console.log("to", to)  
  
        for (let hook of this.beforeHooks) await hook(from, to);  
  
        this.currentUrl = path;  
        this.handleRender();  
  
        for (let hook of this.afterHooks) await hook(to);  
    }  
  
    handleRender() {  
        const route = this.routes[this.currentUrl];  
        if (route) {  
            route.render();  
        } else {  
            this.routes['/404'].render();  
        }  
    }  
  
    getCurrentPath() {  
        if (this.mode === 'history') {  
            return window.location.pathname;  
        } else if (this.mode === 'hash') {  
            return window.location.hash.slice(1) || '/';  
        }  
    }  
  
    beforeEach(hook) {  
        this.beforeHooks.push(hook);  
    }  
  
    afterEach(hook) {  
        this.afterHooks.push(hook);  
    }  
  
    async navigate(path) {  
        if (this.mode === 'history') {  
            history.pushState({}, '', path);  
        } else if (this.mode === 'hash') {  
            window.location.hash = path;  
        }  
        await this.routeChanged();  
    }  
}

// 初始化路由器  
  const router = new Router({  
    mode: 'history', // 使用 history 模式  
    currentUrl: '/' // 设置初始URL为首页  
  });  
  
  // 绑定按钮点击事件到路由导航  
  document.getElementById('home-btn').addEventListener('click', () => {  
    router.navigate('/');  
  });  
  
  document.getElementById('about-btn').addEventListener('click', () => {  
    router.navigate('/about');  
  });  
  
  document.getElementById('not-found-btn').addEventListener('click', () => {  
    router.navigate('/non-route'); // 故意导航到一个不存在的路由  
  });  
              
            
!
999px

Console