# Routing

# Official Router

For most Single Page Applications, it's recommended to use the officially-supported vue-router library. For more details, see vue-router's documentation.

# 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:

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 SimpleRouterApp = {
  data: () => ({
    currentRoute: window.location.pathname
  }),

  computed: {
    CurrentComponent () {
      return routes[this.currentRoute] || NotFoundComponent
    }
  },

  render () {
    return Vue.h(this.CurrentComponent)
  }
}

Vue.createApp(SimpleRouterApp).mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

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

# Integrating 3rd-Party Routers

If there's a 3rd-party router you prefer to use, such as Page.js or Director, integration is similarly straightforward. Here's a complete example using Page.js.

Deployed on Netlify.
Last updated: 7/19/2020, 3:48:09 PM