Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写vue-router路由 #112

Open
GGXXMM opened this issue Mar 11, 2022 · 0 comments
Open

手写vue-router路由 #112

GGXXMM opened this issue Mar 11, 2022 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Mar 11, 2022

实现思路

首先分析vue-router解决的问题:用户点击跳转链接内容切换,页面不刷新。朝着这个方向思考,手写vue-router路由的思路如下:

  1. 借助hash或history api实现url跳转页面不刷新
  2. 同时监听hashchange事件或者popstate事件处理跳转
  3. 根据hash值或是state值从routes表中匹配对应component并渲染

具体实现

  1. 首先定义一个 createRouter 函数,返回路由器实例,实例内部做的逻辑:
    • 保存用户传入的配置项
    • 监听hash或者popstate事件
    • 回调里根据path匹配对应路由
  2. 将router定义成一个vue插件,内部做两件事:
    • 定义2个全局组件:vue-link 和 vue-view,分别实现页面跳转和内容显示
    • 定义2个全局变量:$route和$router,组件内可以访问当前路由和路由器实例

源码实现

createRouter如何创建实例:
https://github1s.com/vuejs/router/blob/HEAD/src/router.ts#L355-L356
history模式,事件监听:
https://github1s.com/vuejs/router/blob/HEAD/src/history/html5.ts#L57
hash模式,事件监听:
https://github1s.com/vuejs/router/blob/HEAD/src/history/hash.ts#L31
页面跳转routerLink:
https://github1s.com/vuejs/router/blob/HEAD/src/RouterLink.ts#L184-L185
内容显示routerView:
https://github1s.com/vuejs/router/blob/HEAD/src/RouterView.ts#L43-L44

@GGXXMM GGXXMM added the vue label Mar 14, 2022
@GGXXMM GGXXMM changed the title 手写vue-router(思路) 手写vue-router Mar 14, 2022
@GGXXMM GGXXMM changed the title 手写vue-router 手写vue-router路由 Mar 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant