import { ref, inject } from 'vue'
const ROUTER_KEY = '__router__'
function createRouter(options) {
return new Router(options)
}
function useRouter() {
return inject(ROUTER_KEY)
}
function createWebHashHistory() {
function bindEvents(fn) {
window.addEventListener('hashchange', fn)
}
console.log(window.location.hash);
return {
bindEvents,
url: window.location.hash.slice(1) || '/'
}
}
import RouterLink from "./RouterLink.vue";
import RouterView from "./RouterView.vue";
class Router {
constructor(options) {
this.history = options.history
this.routes = 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)
app.component('router-link', RouterLink)
app.component('router-view', RouterView)
}
}
export { createRouter, useRouter, createWebHashHistory }
<template>
<a :href="'#'+props.to">
<slot />
</a>
</template>
<script setup>
import {defineProps} from 'vue'
let props = defineProps({
to:{type:String,required:true}
})
</script>
<template>
<component :is="component"></component>
</template>
<script setup>
import { computed } from "vue";
import { useRouter } from "../grouter/index";
let router = useRouter();
console.log(router);
const component = computed(() => {
const route = router.routes.find(
(route) => route.path === router.current.value
);
return route ? route.component : null;
});
console.log(component);
</script>
import { createWebHashHistory, createRouter } from "./grouter/index";
import Home from '../pages/Home.vue'
import About from '../pages/About.vue'
const routes = [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
},
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router