Skip to content
Search

Vue:render

lastmod 2021-07-08created 2021-07-082 edits

Simple routing in Vue.js

The first thing to handle in a single-page application (SPA) is routing. On the server, routing means serving the static file that matches the URI. Implementing this in the browser is the core of SPA development.

The idea is simple: change the DOM in the browser according to the request URI. The Scaling Up section of the official Vue.js documentation has an implementation.

Create three components, one per route.

const Home = { template: "<p>home page</p>" }
const About = { template: "<p>about page</p>" }
const NotFound = { template: "<p>Page not found</p>" }

We want to render these three components, switching between them according to the path. So we need a dictionary of paths and components.

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

This creates a component dictionary for the root ('/') path and the about ('/about') path.

Besides el and data, the Vue instance options object also has a render property. It is actually a function. The render function is a function that receives a DOM-creating function such as createElement as an argument. When you pass a component options object to the function h(), Vue.js draws the component on the screen. (It attaches the component to the mounting point.)

If you make the render() function behave dynamically according to the request path, you can effectively show different screens per route.

new Vue({
  /* 생략 */

  render(h) {
    return h(this.ViewComponent)
  },
})

The render() function calls h(), passing a computed property called ViewComponent as the argument.

new Vue({
  /* 생략 */

  computed: {
    ViewComponent() {
      return routes[window.location.pathname] || NotFound
    },
  },

  /* 생략 */
})

ViewComponent looks up the component for the current path in the routes dictionary and returns it. For an undefined path, it returns the NotFound component.

The full code is as follows:

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) }
})

See also

author Zer0 sitemap