VUE - Vue-Router 原理实现

727 阅读3分钟

main.js

new Vue({
    router,
    render: h => h(App)
}).$mount('#app')

问题:创建 Vue 实例时传入的 router 的作用是什么?

答:会给 vue 实例注入两个属性

  • $route 路由规则
  • $router 路由对象

01 动态路由

方式1

{
    path: '/detail/:id',
    name: 'Detail',
    component: () => import(/* webpackChunkName: "detail" */ '../views/Detail.vue')
}

通过当前路由规则,获取数据
$route.params.id

方式2

{
    {
    path: '/detail/:id',
    name: 'Detail',
    // 开启 props,会把 URL 中的参数传递给组件
    // 在组件中通过 props 来接收 URL 参数
    props: true,
    component: () => import(/* webpackChunkName: "detail" */ '../views/Detail.vue')
}

路由规则中开启 props 传参
export default {
    props: ['id']
}

02 嵌套路由

image.png

router.js

// 嵌套路由
  {
    path: '/',
    component: Layout,
    children: [
      {
        name: 'index',
        path: '',
        component: Index
      },
      {
        name: 'detail',
        path: 'detail/:id',
        props: true,
        component: () => import('@/views/Detail.vue')
      }
    ]
  }

03 编程式导航

// 字符串
router.push('home')

// 对象
router.push({ path: 'home' })

// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})

// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

vue的编程式的导航

HashHistory 模式的区别

HTML5 History 模式

1. 表现形式的区别

  • Hash 模式 - 带 #
    • https://www.hnufw.com/#/playlist?id=3102961863
  • History 模式 - 需要服务端配合使用
    • https://www.hnufw.com/playlist/3102961863

2. 原理区别

  • Hash 模式是基于锚点,以及 onhashchange 事件
  • History 模式是基于 HTML5 中的 History API
    • history.pushState() - IE10 以后才支持
    • history.replaceState()

pushState方法和push方法的区别
调用push方法的时候,路径发生变化 ,这个时候会向服务器发送请求;
调用pushState不会发送请求,只会改变浏览器地址栏中的地址,并且把这个地址记录到历史记录里面来

3. History 模式的使用

router.js

const router = new VueRouter({
    mode: 'history',
    routes: []
})
  • History 需要服务器的支持
  • 因为在单页应用中,服务端不存在 http://www.testurl.com/login 这样的地址会返回找不到该页面
  • 所以在服务端应该除了静态资源外都返回单页面应用的 index.html

History 模式的 Node.js 服务器配置

const path = require('path')
// 导入处理 history 模式的模块
const history = require('connect-history-api-fallback')
// 导入 express
const express = require('express')

const app = express()
// 注册处理 history 模式的中间件
app.use(history())
// 处理静态资源的中间件,网站根目录 ../web
app.use(express.static(path.join(__dirname, '../web')))

// 开启服务器,端口是 3000
app.listen(3000, () => {
  console.log('服务器开启,端口:3000')
})

Vue Router 实现原理

render

Vue 的构建版本

  • 运行时版:不支持 template 模板,需要打包的时候提前编译
  • 完整版:包含运行时和编译器,体积比运行时版大 10KB 左右 ,程序运行的时候把模板转换成 render 函数

vue-cli 创建的默认是运行时版

浏览器控制台显示:
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

如何解决这个问题? (看不懂执行下就知道了!)

vue官方 的 vue.config.js

vue.config.js
根目录下的vue.config.js(没有新创建)

module.exports = {
    runtimeCompiler: true
}

Hash 模式

  • https://www.hnufw.com/#/playlist?id=3102961863
  • URL# 后面的内容作为路径地址
  • 监听 hashchange 事件
  • 根据当前路由地址找到对应组件重新渲染

History 模式

  • https://www.hnufw.com/playlist/3102961863
  • 通过 history.pushState() 方法改变地址栏
  • 监听 popstate 事件
    • 当调用 pushstatereplacestate 不会触发该事件
    • 前进和后退才会触发
  • 根据当前路由地址找到对应组件重新渲染

模拟实现

image.png

实现 router-link
// 使用 render
initComponents (Vue) {
    // 创建 router-link组件
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          }
        }, [this.$slots.default])
      }
    })
  }

实现 router-view
initComponents (Vue) {
    // 创建 router-link组件
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          history.pushState({}, '', this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    const self = this
    Vue.component('router-view', {
      render (h) {
        const component = self.routerMap[self.data.current]
        return h(component)
      }
    })
  }
实现 initEvent
initEvent () {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })
  }

完整代码如下


let _Vue = null;

class VueRouter {
    static install (vue) {

        //1 判断当前插件是否被安装
        if(VueRouter.install.installed) {
            return;
        }

        VueRouter.install.installed = true;

        //2 把Vue的构造函数记录在全局
        _Vue = vue;
        //3 把创建Vue的实例传入的router对象注入到Vue实例
        // _Vue.prototype.$router = this.$options.router

        _Vue.mixin({
            beforeCreate () {
                console.log(this.$options);
                if(this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                }
            }
        });
    }

    constructor (options) {
        this.options = options;
        this.routeMap = {};

        // observable 方法,
        this.data = _Vue.observable({
            // 默认地址是 "/"
            current: '/'
        });

        this.init();
    }

    init () {
        this.createRouteMap();
        this.initComponent(_Vue);
        this.initEvent();
    }


    createRouteMap () {
        // 遍历所有的路由规则 把路由规则解析成键值对的形式存储到routeMap中
        console.log(this.options);
        /**
         * {
                path: '/',
                name: 'Home',
                component: Home
            },
         */
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        });
    }

    initComponent (Vue) {
        // 记录当前函数的this
        const self = this;

        Vue.component("router-link", {
            props: {
                to: String
            },
            render (h) {
                return h("a", {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickhander
                    }
                }, [this.$slots.default]);
            },
            methods: {
                clickhander (e) {
                    // 把当前的route地址 设置为 浏览器地址
                    history.pushState({}, '', this.to);

                    // 把当前的route地址 设置为 当前vue的设置地址
                    this.$router.data.current = this.to

                    // 禁止a标签跳转页面的默认动作
                    e.preventDefault()
                }
            }
        })

        Vue.component ('router-view', {
            render (h) {
                // 查找当前的路由
                const cm = self.routeMap[self.data.current];
                return h(cm)
            }
        })
    }

    initEvent () {
        window.addEventListener('popstate', () => {
            this.data.current = window.location.pathname;
        })
    }
}

export default VueRouter