路由
对于大多数单页面应用,都推荐使用官方支持的vue-router 库
。
从零开始简单的路由
如果你只需要一个简单的页面路由,而不想为此引入一整个路由库,你可以通过动态组件的方式,监听浏览器hashchange
事件或使用HTML5 History API
来更新当前组件。
<script setup> import { ref, computed } from 'vue' import Home from './Home.vue' import About from './About.vue' import NotFound from './NotFound.vue' const routes = { '/': Home, '/about': About } 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>