Vue 3.0 路由

2021-07-16 11:44 更新

#官方 Router

對于大多數(shù)單頁面應(yīng)用,都推薦使用官方支持的 vue-router 庫。更多細(xì)節(jié)可以移步 vue-router 文檔。

#從零開始簡單的路由

如果你只需要非常簡單的路由而不想引入一個功能完整的路由庫,可以像這樣動態(tài)渲染一個頁面級的組件:

  1. const NotFoundComponent = { template: '<p>Page not found</p>' }
  2. const HomeComponent = { template: '<p>Home page</p>' }
  3. const AboutComponent = { template: '<p>About page</p>' }
  4. const routes = {
  5. '/': HomeComponent,
  6. '/about': AboutComponent
  7. }
  8. const SimpleRouter = {
  9. data: () => ({
  10. currentRoute: window.location.pathname
  11. }),
  12. computed: {
  13. CurrentComponent() {
  14. return routes[this.currentRoute] || NotFoundComponent
  15. }
  16. },
  17. render() {
  18. return Vue.h(this.CurrentComponent)
  19. }
  20. }
  21. Vue.createApp(SimpleRouter).mount('#app')

結(jié)合 HTML5 History API,你可以建立一個麻雀雖小但是五臟俱全的客戶端路由器??梢灾苯涌?a rel="external nofollow" target="_blank" target="_blank" rel="nofollow">實(shí)例應(yīng)用。

#整合第三方路由

如果你有更偏愛的第三方路由,如 Page.js 或者 Director,整合起來也一樣簡單。這里有一個使用了 Page.js 的完整示例。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號