Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vue.js 2.0 route


May 07, 2021 Vue.js 2.0


Table of contents


Vue.js 2.0 Official Route

For most single-page applications, the officially supported vue-router library is recommended. More details can be found in the vue-router documentation.

Simple routing from scratch

If you only need very simple routing without having to introduce an entire routing library, you can dynamically render 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) }
})

Combined with the HTML5 History API, you can build a very basic but fully functional client router. You can look directly at the instance app.

Consolidate third-party routes

If you have a third-party route you like very much, .js Page or Director, consolidation is simple. Here's a .js with Page.