手写vue-router

vueRouter

(引用Vue Router 的官方介绍)Vue Router 是 Vue 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
嵌套的路由/视图表
模块化的、基于组件的路由配置
路由参数、查询、通配符
基于 Vue.js 过渡系统的视图过渡效果
细粒度的导航控制
带有自动激活的 CSS class 的链接
HTML5 历史模式或 hash 模式,在 IE9 中自动降级
自定义的滚动条行为

实现router插件

注册组件实现install方法

let Vue;//保存Vue实例
//1、实现插件
class VueRouter {
};
//2、插件要实现一个install方法
VueRouter.install = function(_Vue){
};
//3、导出插件
export default VueRouter;

这段是做一个插件必须要的。

注册组件routerview和routerlink

Vue.component("router-view",{
	render(h){
		let component = null;//定义一个空的component
		const { current, options } = this.$router;//读取路由
		const route = options.routes.find((route) => { route.path === current });//如果路由匹配
		if(route){
			component = route.component;//获取路由记录的component
		}
		return h(component)//h函数渲染
	}
});

Vue.component("router-link",{
	props:{
		to:{
			type:String,
			required:true
		}
	},//必须先传入一个to的地址变量
	render(h){
		return h("a",{ attrs: { href: "#" + this.to }},this.$slots.default);//h函数渲染a节点,用来跳转Url
	}
});

获取router提供给routerview

//注册Router实例
//通过全局混入的方法获得router
Vue.mixin({
	beforeCreate(){
		//仅需要在根组件获取一次
		//this指向Vue,根组件可以获取到$options里的router
		//不需要在每个页面都引用
		if(this.$options.router){
			Vue.prototype.$router = this.$options.router;//将router挂载到Vue实例中
		}
	}
})

获取当前的hash

//响应式获取当时的Url
//响应式的两种方法
//1、使用Vue(){
//	data(){
//}}
//2、使用defineReactive
Vue.util.defineReactive(
	this,
	"current",
	window.location.hash.slice(1) || "/"
)
//监控Url变化
window.addEventListener("hashchange",() => {
	this.current = window.location.hash.slice(1);//获取Url#后的内容
})

完成routerview渲染页面

Vue.component("router-view",{
	render(h){
		let component = null;//定义一个空的component
		const { current, options } = this.$router;//读取路由
		const route = options.routes.find((route) => { route.path === current });//如果路由匹配
		if(route){
			component = route.component;//获取路由记录的component
		}
		return h(component)//h函数渲染
	}
});

其他

问:为什么routerView和Vue强相关?
回答:因为routerView是vue插件,方法内多次调用vue实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值