• Vue-Router核心实现原理


    vue-router的实现原理简介
    如何在vue中使用vue-router?
    1.Vue使用插件,即调用Vue的use方法;

    // router.js 
    Vue.use(Router);
    

    2.实例化router,并配置router的配置对象,含routes路由;

    // router.js 
    export default new Router({
        mode:"hash",
        routes:[
            {
                path:"/hello",
                component:HelloWorld
            },
            {
                path:"/",
                component:VuexTest
            },
            {
                path:"/form",
                component:Form
            }
        ]
    })
    

    3.在vue实例上配置router实例;

    // main.js
    import router from "./config/router";
    new Vue({
      router,
      render: h => h(App),
    }).$mount('#app')
    

    4.使用

    <template>
      <div id="app">
        <router-link to="/">home</router-link>|
        <router-link to="/form">form</router-link>|
        <router-link to="/hello">HelloWorld</router-link>
        <router-view></router-view>
      </div>
    </template>
    

    5.效果
    点击home,form,helloWorld可以切换路由页面。

    以上的几个步骤,vue-router内部都做了什么?
    我们需要明白的是,router-link和router-view是两个Vue全局组件,必定是在vue-router中实现了全局定义两个组件,他们分别用来跳转路由和展示路由对应的组件内容。

    我们点击了router-link时导致路由变了,vue-router内部必然是在监听路由变化,根据路由规则找到匹配的组件,然后在router-view中渲染。

    所以,路由切换最终是页面的不同组件的展示,而没有真正去刷新页面。

    那么接下来说vue-router核心实现原理:

    目标:
    1.实现一个静态install方法,因为作为插件都必须有这个方法,给Vue.use()去调用;
    2.可以监听路由变化;
    3.解析配置的路由,即解析router的配置项routes,能根据路由匹配到对应组件;
    4.实现两个全局组件router-link和router-view;(最终落地点)

    核心代码实现简版:

    let Vue;
    class KVueRouter {
        constructor(options){
            this.$options=options;
            this.$routerMap={};//{"/":{component:...}}
            // url 响应式,当值变化时引用的地方都会刷新
            this.app = new Vue({
                data:{
                    current:"/"
                }
            });
        }
        // 初始化
        init(){
            // 监听事件
            this.bindEvent();
            // 解析路由
            this.createRouteMap();
            // 声明组件
            this.initComponent();
        }
        bindEvent(){
            window.addEventListener('hashchange',this.onHashchange.bind(this));
        }
        onHashchange(){
            this.app.current = window.location.hash.slice(1) || "/";
        }
        createRouteMap(){
            this.$options.routes.forEach(route=>{
                this.$routerMap[route.path]=route;
            })
        }
        initComponent(){
            Vue.component('router-link',{
                props:{
                    to:String,
                },
                render(h){
                    return h('a',{attrs:{href:'#'+this.to}},[this.$slots.default])
                }
            });
            Vue.component('router-view',{
                render:(h)=>{
                  //这里使用了data中的 this.app.current,根据vue相应式原理,当变化 this.app.current时
                  //这里会监听并发生变化
                    const Component = this.$routerMap[this.app.current].component;
                    return h(Component)
                }
            });
        }
    }
    // 参数是vue构造函数,Vue.use(router)时,执行router的install方法并把Vue作为参数传入
    KVueRouter.install = function(_vue){
        Vue = _vue;
        //全局混入
        Vue.mixin({
            beforeCreate(){//拿到router的示例,挂载到vue的原型上
                if (this.$options.router) {
                    Vue.prototype.$router=this.$options.router;
                    this.$options.router.init();
                }
            }
        })
    }
    export default KVueRouter;
    

    解读如下:

    Vue.use(Router)时,会调用router的install方法并把Vue类传入,混入beforeCreate方法,即在Vue实例化后挂载前在vue原型上挂个$router方法(因为这样后面才能用this.$router.push()...但此处没有实现哦),然后调用router实例的init方法;

    在init中把三件事情都干了,监听路由,解析路由(路由mapping匹配),定义组件;

    需要注意的是,存储当前路由的变量this.app.current非一般的变量,而是借用Vue的响应式定义的,所以当路由变化时只需要给这个this.app.current赋值,而router-view组件刚好引用到这个值,当其改变时所有的引用到的地方都会改变,则得到的要展示的组件也就响应式的变化了

    ====

    作者:变态的小水瓶
    链接:https://www.jianshu.com/p/d59971198082
    来源:简书

  • 相关阅读:
    android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3
    display:inline-block的运用
    图解单片机8位PWM、16位PWM中“位”的含义!
    UVA10006
    [置顶] CF 86D Powerful array 分块算法入门,n*sqrt(n)
    俗人解释 三维渲染 在工作过程
    HDU 4414 Finding crosses(dfs)
    Codeforces 35E Parade 扫描线 + list
    hdu 4374 单调队列
    LeetCode OJ平台Sort Colors讨论主题算法
  • 原文地址:https://www.cnblogs.com/xiaozhumaopao/p/12716266.html
Copyright © 2020-2023  润新知