代码示例:
<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import HomeVue from './components/Home.vue';
import AboutVue from './components/About.vue';
import { ref, computed } from 'vue'
const routes = {
'/': HomeVue,
'/about': AboutVue
}
const currentPath = ref(window.location.hash)
window.addEventListener('hashchange', () => {
currentPath.value = window.location.hash
})
const currentView = computed(() => {
return routes[currentPath.value.slice(1)] || '/' || NotFound
})
</script>
<template>
<a href="#/">Home</a> |
<a href="#/about">About</a> |
<a href="#/non-existent-path">Broken Link</a>
<component :is="currentView" />
</template>
学习:
- 页面是通过computed()实现更新页面,同样也可以是ref等响应式更新;
- 而触发更新事件是由当前页面URL改变,使用的是hashchange;
- href="#/" 中#是锚点指向当前页面;