How to implement simple routing in Vue.js (without external library)?

Technology CommunityCategory: Vue.jsHow to implement simple routing in Vue.js (without external library)?
VietMX Staff asked 3 years ago

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 NotFound = { template: '<p>Page not found</p>' }
const Home = { template: '<p>home page</p>' }
const About = { template: '<p>about page</p>' }

const routes = {
  '/': Home,
  '/about': About
}

new Vue({
  el: '#app',
  data: {
    currentRoute: window.location.pathname
  },
  computed: {
    ViewComponent () {
      return routes[this.currentRoute] || NotFound
    }
  },
  render (h) { return h(this.ViewComponent) }
})

For most Single Page Applications, it’s recommended to use the officially-supported vue-router library.