前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >手写vue-router核心原理

手写vue-router核心原理

原创
作者头像
hellocoder2029
发布2022-09-26 16:23:41
3710
发布2022-09-26 16:23:41
举报
文章被收录于专栏:前端面试题总结

最近也在观察vue3新特性,抽空玩一玩嵌套路由的vue-router,直接上代码

项目目录结构

目录结构
目录结构

代码展示

  • app.vue
代码语言:html
复制
<template>
  <div id="app">
    <div>
      <router-link to="/">Index</router-link> |
      <router-link to="/person">Person</router-link> |
      <router-link to="/person/info">PersonInfo</router-link>
    </div>
    <!-- 一级路由 -->
    <router-view />
  </div>
</template>

<style>
#app{  display: flex;  flex-direction: column;  align-items: center;}
</style>
  • Index.vue
代码语言:html
复制
<template>
  <div class="index">
    <h1>this is index page</h1>
  </div>
</template>
  • Person.vue
代码语言:html
复制
<template>
  <div class="person">
    <h1>this is person page</h1>
     <!-- 二级路由 -->
    <router-view />
  </div>
</template>
  • PersonInfo.vue
代码语言:html
复制
<template>
  <div class="personInfo">
    <h2>this is personInfo page</h2>
  </div>
</template>
vue全家桶视频讲解:进入学习

js文件

  • main.js
代码语言:javascript
复制
import Vue from 'vue'
import App from './App.vue'
import router from './router'

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
  • babel.config.js
  • 需要添加babel依赖支持新语法,如可选链
  • npm install --save-dev @babel/core @babel/cli
  • npm install --save-dev @babel/plugin-proposal-optional-chaining
代码语言:text
复制
module.exports = {
  presets: [    '@babel/preset-env'  ],
  plugins: ['@babel/plugin-proposal-optional-chaining']
}
  • router目录下文件
  • index.js
代码语言:javascript
复制
import Vue from "vue";
import VueRouter from "./vue-router";
import Index from "../views/Index.vue";
import Person from "../views/Person.vue";
import PersonInfo from "../views/PersonInfo.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Index",
    component: Index
  },
  {
    path: "/person",
    name: "Person",
    component: Person,
    children:[
      {
        path: "/person/info",
        name: "PersonInfo",
        component: PersonInfo
      }
    ]
  }
];

const router = new VueRouter({
  routes
});

export default router;
  • vue-router.js 这里先借助Vue的工具Vue.util.defineReactive实现数据响应式,后续再手撕这个库
代码语言:text
复制
import routerLink from "./router-link";
import routerView from "./router-view";

let Vue;
class VueRouter {
  constructor(options) {
    this.$options = options

    this.current = window.location.hash.slice(1) || "/"

    // 设置响应式数组数据
    Vue.util.defineReactive(this, "routerArray", [])

    // 监听hash值变化
    window.addEventListener("hashchange", this.hashChange.bind(this))

    this.getRouterArray()
  }

  hashChange() {
    this.current = window.location.hash.slice(1) || "/"
    this.routerArray = []
    this.getRouterArray()
  }

  getRouterArray(routes) {
    routes = routes || this.$options.routes
    for (const route of routes) {
      if (this.current === '/' && route.path === '/') {
        this.routerArray.push(route)
        return
      }

      if (this.current.indexOf(route.path) !== -1 && route.path !== '/') {
        this.routerArray.push(route)
        if (route.children) {
          // 递归子路由
          this.getRouterArray(route.children)
        }
        return
      }
    }
  }
}

VueRouter.install = function(_Vue) {
  Vue = _Vue

  // Vue全局混入,等new Vue中的router实例创建之后挂载到Vue上
  Vue.mixin({
    beforeCreate() {
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router
      }
    },
  });

  // 注册router-link和router-view全局组件
  Vue.component("router-link", routerLink)
  Vue.component("router-view", routerView)
}

export default VueRouter
  • router-link.js
代码语言:javascript
复制
export default {
  props: {
    to: {
      type: String,
      required: true
    }
  },
  render(h) {
    return h(
      "a",
      {
        attrs: {
          href: "#" + this.to,
        },
      },
      this.$slots.default
    );
  }
};
  • router-view.js
代码语言:javascript
复制
export default {
  render(h) {
    // 设置嵌套路由标识
    this.$vnode.data.rv = true

    // 嵌套路由设置深度
    let depth = 0
    let parent = this.$parent
    while (parent) {

      // 上级还有嵌套路由标识rv为true的,深度加一
      if (parent.$vnode?.data?.rv) {
        depth++
      }
      parent = parent.$parent
    }

    // 简单处理
    const route = this.$router.routerArray[depth]
    return h(route?.component);
  }
};

好了,今天就玩到这里了,下次再玩别的哈

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 项目目录结构
  • 代码展示
    • vue全家桶视频讲解:进入学习
    • js文件
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档