vue-router@4.x实现分析

本文最后更新于:2022年4月21日 上午

简单实现

vue-router

import { ref, inject } from "vue";
const ROUTER_KEY = Symbol();

function useRouter() {
	return inject(ROUTER_KEY);
}

function createRouter(options) {
	return new Router(options);
}

function createWebHashHistory() {
	function bindEvent(fn) {
		window.addEventListener("hashchange", fn);
	}
	const url = window.location.hash.slice(1) || "/";

	return {
		bindEvents,
		url,
	};
}

class Router {
	constructor(options) {
		this.history = options.history;
		this.router = options.routes;
		this.current = ref(this.history.url);

		this.history.bindEvents(() => {
			this.current.value = window.location.hash.slice(1);
		});
	}

	install(app) {
		app.provide(ROUTER_KEY, this);
	}
}

export { createRouter, createWebHashHistory, useRouter };

router-view

<template>
	<component :is="comp"></component>
</template>
<script setup>
import { computed } from "vue";
import { useRouter } from "👆";
const router = useRouter();
const comp = computed(() => {
	const route = router.routes.find((route) => route.path === router.current.value); // 使用path查找
	return route ? route.component : null;
});
</script>
<template>
	<a :href="'#' + props.to">
  <!-- 简单的改变地址栏hash -->
		<slot />
	</a>
</template>
<script setup>
const props = defineProps({
	to: {
		type: String,
		required: true,
	},
});
</script>

vue-router@4.x实现分析
http://yoursite.com/2022/03/22/[源码]vue3-router/
作者
tatekii
发布于
2022年3月22日
许可协议