vue-router的history模式

35 阅读1分钟
<body>
    <div>
        <!-- 相当于router-link -->
        <a href="/">首页</a>
        <a href="/user">用户</a>
        <a href="/cart">购物车</a>
    </div>
    <!-- 相当于router-view -->
    <div id="view"></div>
    <script>
        var router = {
            // 定义路由表
            routes: {},
            route(path, cb) {
                this.routes[path] = cb
            },
            go(path) {
                // 更改url
                // 传递个path参数
                history.pushState({ path }, null, path)
                // 触发回调
                this.routes[path] && this.routes[path]()
            },
            // 监听前进和后退,并且从 state中取出传递过来的参数
            init() {
                window.addEventListener('popstate', (e) => {
                    var path = e.state ? e.state.path : '/'
                    this.routes[path] && this.routes[path]()
                })
            }
        }

        router.init()

        // 用户使用
        var view = document.getElementById('view')
        var links = document.querySelectorAll('a')
        // 添加点击事件
        links.forEach((link) => {
            link.addEventListener('click', function (e) {
                // 自己写的函数 把path 传递进去
                router.go(this.getAttribute('href'))
                // 阻止默认跳转事件
                e.preventDefault()
            })
        })
        router.route('/', () => {
            view.innerHTML = '首页内容'
        })
        router.route('/user', () => {
            view.innerHTML = '用户内容'
        })
        router.route('/cart', () => {
            view.innerHTML = '购物车内容'
        })

    </script>
</body>

hash的时候是监听hashChange事件,通过获取到hash值,对hash值做些处理,然后匹配相应的component。 而history模式是阻止默认事件的跳转,手动绑定click事件,通过获取到的href属性值和pushState方法进行路由跳转和相应回调函数的执行。