VUE3 入门教程 Vue 3.0 路由

2024-02-25 开发教程 VUE3 入门教程 匿名 0

#官方 Router

对于大多数单页面应用,都推荐使用官方支持的 vue-router 库。更多细节可以移步 vue-router 文档

#从零开始简单的路由

如果你只需要非常简单的路由而不想引入一个功能完整的路由库,可以像这样动态渲染一个页面级的组件:

const NotFoundComponent = { template: '<p>Page not found</p>' }
const HomeComponent = { template: '<p>Home page</p>' }
const AboutComponent = { template: '<p>About page</p>' }
const routes = {
'/': HomeComponent,
'/about': AboutComponent
}
const SimpleRouter = {
data: () => ({
currentRoute: window.location.pathname
}),
computed: {
CurrentComponent() {
return routes[this.currentRoute] || NotFoundComponent
}
},
render() {
return Vue.h(this.CurrentComponent)
}
}
Vue.createApp(SimpleRouter).mount('#app')

结合 HTML5 History API,你可以建立一个麻雀虽小但是五脏俱全的客户端路由器。可以直接看实例应用

#整合第三方路由

如果你有更偏爱的第三方路由,如 Page.js或者 Director,整合起来也一样简单。这里有一个使用了 Page.js 的完整示例