Three Ways to Implement Routing in Vue

✍🏼 Written on Jun 12, 2016   
❗️ Note: it has been days since this article was written, please be aware of its timeliness

Introduction

The Vue learning summary is basically complete. Next, I’ll supplement some fragmented knowledge. Today, let’s discuss three implementation methods of Vue Router.

View the complete project code (This project contains other Vue test code such as Vue Plugin, etc.)

Via the render Function

The basic idea is that the render function renders component content based on the address bar path. By using HTML5’s history.pushState and listening to popstate events, it can achieve routing functions like direct address access, browser back/forward navigation, and link-click jumps.

Advantages:

  1. Non-existent addresses can be redirected to a 404.vue page.

Disadvantages:

  1. Browsers that don’t support the HTML5 history.pushState API cannot be polyfilled.
  2. The rendering of the render function cannot be cached.

Note: If using transition animations, the root element exists in default.vue. Pay attention to the difference in the code compared to the method below.

View specific code

Via the is Attribute of the component

The principle is the same as above, but the render function is replaced with a component.

The component has an is attribute, which specifies which template the component should load. This attribute can be dynamically set based on the address bar path through custom logic.

Advantages:

  1. The component can be cached using the keep-alive attribute, making it more efficient than the render function above.

Disadvantages:

  1. Browsers that don’t support the HTML5 history.pushState API cannot be polyfilled.
  2. Non-existent route addresses (e.g., 404) cannot be rendered (hence, this Demo doesn’t include a 404.vue like the previous method).

Note: If using transition animations, the root element exists in tpl.html. Pay attention to the difference in the code compared to the method above.

View specific code

Via the VueRouter Plugin

VueRouter is an official plugin that perfectly fulfills all requirements.

Advantages:

  1. All necessary features are included.

Disadvantages:

  1. To polyfill pushState, a # is appended to the path to enable routing functionality, which is not true routing but merely a hash value change.

View specific code

- EOF -
Originally published at: Three Ways to Implement Routing in Vue - Xheldon Blog