Skip to content
On this page

路由设计模式

哈希(hash)路由

原理:每一次路由跳转,都是改变页面的hash值;并且监听hashchange事件,渲染不同的内容!!

html
<nav class="nav-box">
    <a href="#/">首页</a>
    <a href="#/product">产品中心</a>
    <a href="#/personal">个人中心</a>
</nav>
<div class="view-box"></div>

<!-- IMPORT JS -->
<script>
    // 路由容器
    const viewBox = document.querySelector('.view-box');
    // 路由表
    const routes = [{
        path: '/',
        component: '首页内容'
    }, {
        path: '/product',
        component: '产品中心内容'
    }, {
        path: '/personal',
        component: '个人中心内容'
    }];

    // 页面一加载,我们设置默认的hash值
    location.hash = '/';

    // 路由匹配的方法
    const routerMatch = function routerMatch() {
        let hash = location.hash.substring(1),
            text = "";
        routes.forEach(route => {
            if (route.path === hash) {
                text = route.component;
            }
        });
        viewBox.innerHTML = text;
    };
    routerMatch();
    window.addEventListener('hashchange', routerMatch);
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

浏览器(history)路由

原理:利用H5的HistoryAPI完成路由的切换和组件的渲染! https://developer.mozilla.org/zh-CN/docs/Web/API/History_API

html
<nav class="nav-box">
    <a href="/">首页</a>
    <a href="/product">产品中心</a>
    <a href="/personal">个人中心</a>
</nav>
<div class="view-box"></div>

<!-- IMPORT JS -->
<script>
    const viewBox = document.querySelector('.view-box'),
        navBox = document.querySelector('.nav-box');
    const routes = [{
        path: '/',
        component: '首页内容'
    }, {
        path: '/product',
        component: '产品中心内容'
    }, {
        path: '/personal',
        component: '个人中心内容'
    }];

    // 路由匹配
    const routerMatch = function routerMatch() {
        let path = location.pathname,
            text = "";
        routes.forEach(route => {
            if (route.path === path) {
                text = route.component;
            }
        });
        viewBox.innerHTML = text;
    };

    history.pushState({}, "", "/");
    routerMatch();

    // 控制路由切换
    navBox.addEventListener('click', function (ev) {
        let target = ev.target;
        if (target.tagName === 'A') {
            // 阻止默认行为
            ev.preventDefault();
            // 实现路由的跳转
            history.pushState({}, "", target.href);
            routerMatch();
        }
    });

    /* 
     popstate事件触发时机:
     1)点击浏览器的前进、后退按钮
     2)调用history.go/forward/back等方法
     注意:history.pushState/replaceState不会触发此事件
     */
    window.addEventListener('popstate', routerMatch);
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
沪ICP备20006251号-1