• vue3的vue-router原理


    真实vue-router的基本使用

    vue-router官网链接

    在main.js文件下,给挂载到实例上

    const app = createApp()
    import router from './router'
    app.use(router).mount('#app')
    
    • 1
    • 2
    • 3
    import {createRouter,createWebHistory} from 'vue-router'
    const Home = {
      template: '<div>Index</div>',
    }
    const A = {
      template: '<div>User {{ $route.params.id }}</div>',
    }
    const routes = [
    	{
    		path:'/',
    		component:Home
    	},
    	{
    		path:'/aaa/:id',
    		component:A
    	},
    	{
    		path:'/bbb',
    		component:B
    	}
    ]
    const router = {
    	routes,
    	history : createWebHashHistory() // 另一种是createWebHistory
    }
    router.beforeEach((to,from,next)=>{
    	next()
    })
    export default router
    
    • 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

    动态路由,在组件内部如何去监测路由变化

    export default {
      mounted(){
        console.log(this.$route);// 入下图所示
        this.$watch(
          ()=> this.$route.params,
          (a,b)=>{
            console.log(a,b);// {id: '444'} {id: '333'}
          }
        )
      },
      async beforeRouteUpdate(to, from) {
        // 只有在动态路由更新时触发这个,
        // 从另外一个路由跳转到该动态路由不会触发这个函数
        // 刷新页面也不会触发这个函数
        console.log(to);// 数据结构同 this.$route
      },
    }
    /*
    {
        "fullPath": "/home/444?x=111&y=222",
        "path": "/home/444",
        "query": {
            "x": "111",
            "y": "222"
        },
        "hash": "",
        "params": {
            "id": "444"
        },
        "matched": [
            {
                "path": "/home/:id",
                "meta": {},
                "props": {
                    "default": false
                },
                "children": [],
                "instances": {
                    "default": null
                },
                "leaveGuards": {},
                "updateGuards": {},
                "enterCallbacks": {},
                "components": {
                    "default": {
                        "__hmrId": "19e6bc5a",
                        "__file": "E:/html/vue-element-ui/vue3-vite-pr/src/components/home2.vue"
                    }
                }
            }
        ],
        "meta": {},
        "href": "#/home/444?x=111&y=222"
    }
    */
    
    • 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

    vue-router基本实现

    vue-router开发源码
    mini-vue-router代码

    简单实现的mini-vue-router代码如下

    App.vue

    <template>
      <div>
        <router-link to="/">Go to Home</router-link> |
        <router-link to="/about">Go to About</router-link>
        <router-view></router-view>
      </div>
    </template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    main.js

    import { createApp } from "vue";
    import App from "./App.vue";
    import router from "./router";
    createApp(App).use(router).mount("#app");
    
    • 1
    • 2
    • 3
    • 4

    router / index.js

    import Home from '../views/Home.vue'
    import About from '../views/About.vue'
    import { createRouter } from './router'
    const routes = [
      {path: '/', component: Home},
      {path: '/about', component: About},
    ]
    const router = createRouter({
      // history: createWebHashHistory(),
      routes
    })
    export default router
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    router / router.js

    import { ref } from 'vue'
    import RouterLink from './RouterLink'
    import RouterView from './RouterView'
    export function createRouter(options) {
      const router = {
        options, 
        current: ref(window.location.hash.slice(1) || '/'),
        install(app) {
          app.component('RouterLink', RouterLink)
          app.component('RouterView', RouterView)
          app.config.globalProperties.$router = this
        }
      } 
      window.addEventListener('hashchange', () => {
        router.current.value = window.location.hash.slice(1)
      })
      return router
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    router / RouterLink.js

    import { defineComponent, h, unref } from "vue";
    export default defineComponent({
      props: {
        to: {
          type: String,
          required: true,
        },
      },
      setup(props, { slots }) {
        return () => {
          const to = unref(props.to);
          return h(
            "a",
            {
              href: "#" + to,
            },
            slots.default()
          );
        };
      },
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    router / RouterView.js

    import { defineComponent, getCurrentInstance, h, unref } from "vue";
    export default defineComponent({
      setup() {
        return () => {
          const {
            proxy: { $router },
          } = getCurrentInstance();
          let component;
          const route = $router.options.routes.find(
            (route) => route.path === unref($router.current)
          );
          if (route) {
            component = route.component;
            return h(component, "router-view");
          } else {
            return h("div", "");
          }
        };
      },
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  • 相关阅读:
    Qt中使用图像格式对QPainter绘制文字影响
    【html/html5/css/css3知识点】
    数据收集-数据收集软件-数据收集工具免费
    liunx系统安装docker
    抓包day3
    jfinal中如何使用过滤器监控Druid监听SQL执行?
    【计算机系统结构期末复习】第五章
    SUB-1G无线射频收发器芯片DP4301/CMT2300A无线遥控器应用
    案例!快看!电力行业利用IBPS低代码应用开发平台做好数据治理工作
    PerfView专题 (第一篇):如何寻找 C# 热点函数
  • 原文地址:https://blog.csdn.net/formylovetm/article/details/125523151