40 lines
918 B
Markdown

---
title: 不使用vue-router实现简单路由跳转
createTime: 2022/05/29 23:40:45
tags:
- Vue
---
参考[simple-routing-from-scratch](https://vuejs.org/guide/scaling-up/routing.html#simple-routing-from-scratch)
官方给的是 vue2+js 的写法,用 vue3+ts 简单改一下:
```vue
<script setup lang="ts">
import { computed, reactive } from 'vue'
import Gadget from './views/Gadget.vue'
import HelloWorld from './views/HelloWorld.vue'
const data: any = reactive({
currentPath: window.location.pathname,
routes: {
'/': HelloWorld,
'/Gadget': Gadget,
},
})
window.addEventListener('hashchange', () => {
data.currentPath = window.location.hash
})
const currentView = computed(() => {
return data.routes[data.currentPath.slice(1) || '/'] || HelloWorld
})
</script>
<template>
<a href="./">Home</a> | <a href="#/Gadget">Gadget</a> |
<component :is="currentView" />
</template>
```