简易的路由功能实现

这里用到了popstate事件,当活动历史记录条目更改时,将触发popstate事件。MDN解释popstate

html代码

<a href="#/test1">测试1</a>
<a href="#/test2">测试2</a>
<a href="#/test3">测试3</a>

js实现

!{
    cache: {},
    active: null,
    init() {
        this.onPopState()
        addEventListener('popstate', this.onPopState.bind(this))
    },
    onPopState() {
        const path = (location.hash.match(/#\/(\w+)/) || [, 'main'])[1]
        path !== this.active && this.route(path)
    },
    route(path) {
        let active = this.active,
            cache = this.cache

        active in cache && delete cache[active]
        this.active = path
        //可以缓存一个实例对象,例如vue instance,此处缓存path
        cache[path] = path
        console.log(cache);
    }
}.init()

init主要负责添加popstate,为了监听后续的路由地址变化。

onPopStatepopstate的回调,对符合规则的地址使用路由驱动。

route 路由驱动

具体的渲染就不写了,在route中新增对应钩子即可。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注