Routing

Official Router

For most Single Page Applications, it’s recommended to use the officially-supported vue-router libraryRouting - 图1. For more details, see vue-router’s documentationRouting - 图2.

Simple Routing from Scratch

If you only need very simple routing and do not wish to involve a full-featured router library, you can do so by dynamically rendering a page-level component like this:

  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 SimpleRouterApp = {
  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(SimpleRouterApp).mount('#app')

Combined with the History APIRouting - 图3, you can build a very basic but fully-functional client-side router. To see that in practice, check out this example appRouting - 图4.

Integrating 3rd-Party Routers

If there’s a 3rd-party router you prefer to use, such as Page.jsRouting - 图5 or DirectorRouting - 图6, integration is similarly straightforwardRouting - 图7. Here’s a complete exampleRouting - 图8 using Page.js.