Vue 进阶 [五] 手写VueRouter

2023-10-29 18:38

本文主要是介绍Vue 进阶 [五] 手写VueRouter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

人生当自勉,学习需坚持。

定义

Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的链接
  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为

VueRouter使用的核心步骤

步骤一:使用vue-router 插件,router.js

import Router from 'vue-router'
Vue.use(Router)

步骤二:创建Router 实例,router.js

export default new Router({...})

步骤三:在组件上添加该实例,main.js

import router from './router'
new Vue({
router,
}).$mount("#app");

步骤四:添加路由视图 App.vue

<router-view></router-view>

导航:

<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>

vue-router 手动实现

需求分析

  • 作为一个插件存在:实现VueRouter类和install方法
  • 实现两个全局组件:router-view用于显示匹配组件内容,router-link用于跳转
  • 监控url变化:监听hashchange或popstate事件
  • 响应最新url:创建一个响应式的属性current,当它改变时获取对应组件并显示

实现一个插件:创建VueRouter类和install方法

let Vue; // 引用构造函数,VueRouter中要使用
// 保存选项
class VueRouter {
constructor(options) {
this.$options = options;
}
}
// 插件:实现install方法,注册$router
VueRouter.install = function(_Vue) {
// 引用构造函数,VueRouter中要使用
Vue = _Vue;
Vue.mixin({
beforeCreate() {
// 只有根组件拥有router选项
if (this.$options.router) {
// vm.$router
Vue.prototype.$router = this.$options.router;
}
}
});
};
export default VueRouter;

创建router-view和router-link

 zrouter-link.js

export default {props: {to: {type: String,required: true},},render(h) {// <a href="#/about">abc</a>// <router-link to="/about">xxx</router-link>// h(tag, data, children)console.log(this.$slots);return h('a', {attrs: {href: '#' + this.to}}, this.$slots.default)// return <a href={'#' + this.to}>{this.$slots.default}</a>}
}

zrouter-view.js

export default {render(h) {//获取path对应的componentconst {routeMap,current} = this.$router;console.log(routeMap, current);const component = routeMap[current].component || null;return h(component)}
}

监控url变化

定义响应式的current属性,监听hashchange事件

class VueRouter {
constructor(options) {
// current应该是响应式的
Vue.util.defineReactive(this, 'current', '/')
// 定义响应式的属性current
const initial = window.location.hash.slice(1) || '/'
Vue.util.defineReactive(this, 'current', initial)
// 监听hashchange事件
window.addEventListener('hashchange', this.onHashChange.bind(this))
window.addEventListener('load', this.onHashChange.bind(this))
}
onHashChange() {
this.current = window.location.hash.slice(1)
}
}

创建路由映射表

        //创建一个路由映射表this.routeMap = {}options.routes.forEach(route => {this.routeMap[route.path] = route})

较完整代码

import Link from './zrouter-link'
import View from './zrouter-view'
//1、实现一个插件:挂载$router ==>实现install 方法
let Vue
class ZVueRouter {constructor(options) {this.$options = options//需要创建响应式的current属性Vue.util.defineReactive(this, 'current', '/')// this.current = '/'// 监听URL的变化window.addEventListener('hashchange', this.onHashChange.bind(this))window.addEventListener('load', this.onHashChange.bind(this))//创建一个路由映射表this.routeMap = {}options.routes.forEach(route => {this.routeMap[route.path] = route})}onHashChange() {console.log(window.location.hash)this.current = window.location.hash.slice(1)}
}
ZVueRouter.install = function (_Vue) {//保存构造函数,在ZVueRouter中使用Vue = _Vue//挂载$router// 怎么获取根实例中的router 选项 使用全局混入//Vue.mixin({//此处写的生命周期的钩子 会在所有组件中都执行一遍beforeCreate() {// console.log(this)// 确保根实例的时候才执行if (this.$options.router) {Vue.prototype.$router = this.$options.router}},})//任务2、实现两个全局组件router-link 和 router-view// Vue.component('router-link', {//     props: {//         to: {//             type: String,//             required: true,//         },//     },//     render(h) {//         // 希望渲染出一个a 标签//         // h(tag,data,children)//         //<router-link to='/about'></router-link>//         //   console.log(this.$slots)//         return h('a', {//             attrs: {//                 href: "#" + this.to//             }//         }, this.$slots.default)//     },// })// Vue.component('router-view', {//     render(h) {//         // 获取path 对应的component//         // let component = null//         console.log(this)//         console.log('router-view this.$router', this.$router)//         // this.$router.$options.routes.forEach((route) => {//         //     if (route.path === this.$router.current) {//         //         component = route.component//         //     }//         // })//         // 以上这样写每次渲染都需要遍历找一遍 优化//         const {//             routeMap,//             current//         } = this.$router//         const component = routeMap[current].component || null;//         return h(component)//     },// })// 将router-link router-view 单抽取出来Vue.component('router-link', Link)Vue.component('router-view', View)}
export default ZVueRouter

代码地址

https://gitee.com/xiaozhidayu/vue-study-component

https://gitee.com/xiaozhidayu/vue-study-component.git

人生就是一场马拉松。领先时不必沾沾自喜,落后时也不用慌乱着急,此刻的得失成败,不代表最终的成绩。把鲜花和掌声当作前进的动力,把挫折和失败化为奋进的勇气,只要不放弃,再平凡的人生也能创造奇迹

这篇关于Vue 进阶 [五] 手写VueRouter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/302577

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

【 html+css 绚丽Loading 】000046 三才归元阵

前言:哈喽,大家好,今天给大家分享html+css 绚丽Loading!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、信息💡1.简介:💡2.外观描述:💡3.使用方式:💡4.战斗方式:💡5.提升:💡6.传说: 📚三、源代码,上代码,可以直接复制使用🎥效果🗂️目录✍️

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

[MySQL表的增删改查-进阶]

🌈个人主页:努力学编程’ ⛅个人推荐: c语言从初阶到进阶 JavaEE详解 数据结构 ⚡学好数据结构,刷题刻不容缓:点击一起刷题 🌙心灵鸡汤:总有人要赢,为什么不能是我呢 💻💻💻数据库约束 🔭🔭🔭约束类型 not null: 指示某列不能存储 NULL 值unique: 保证某列的每行必须有唯一的值default: 规定没有给列赋值时的默认值.primary key:

计算机毕业设计 大学志愿填报系统 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试

🍊作者:计算机编程-吉哥 🍊简介:专业从事JavaWeb程序开发,微信小程序开发,定制化项目、 源码、代码讲解、文档撰写、ppt制作。做自己喜欢的事,生活就是快乐的。 🍊心愿:点赞 👍 收藏 ⭐评论 📝 🍅 文末获取源码联系 👇🏻 精彩专栏推荐订阅 👇🏻 不然下次找不到哟~Java毕业设计项目~热门选题推荐《1000套》 目录 1.技术选型 2.开发工具 3.功能

Vue3项目开发——新闻发布管理系统(六)

文章目录 八、首页设计开发1、页面设计2、登录访问拦截实现3、用户基本信息显示①封装用户基本信息获取接口②用户基本信息存储③用户基本信息调用④用户基本信息动态渲染 4、退出功能实现①注册点击事件②添加退出功能③数据清理 5、代码下载 八、首页设计开发 登录成功后,系统就进入了首页。接下来,也就进行首页的开发了。 1、页面设计 系统页面主要分为三部分,左侧为系统的菜单栏,右侧

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念