Using the MoonRouter with Moon.js

Using the MoonRouter with Moon.js

Lately I've been using Moon.js in a couple of playground projects, and I was impressed by how easy it is to use the router. In this article, I'll be looking at exactly that.

Let's first start off by creating a new index.html with Moon, MoonRouter and app.js:

<!DOCTYPE html>
<html lang="en">
  <title>Moon.js Router</title>
<script src=""></script>
<script src=""></script>

<script src="app.js"></script>

We can then create a new div where our Moon instance can be mounted. I'll also add the router-view which will be used to inject our route components into:

<div id="app">

Next, inside of app.js I'll be telling Moon that we want to use the MoonRouter plugin:


Then we can define a new MoonRouter instance which maps the routes to our Moon components:

const router = new MoonRouter({
	default: '/',
	map: {
		'/': 'Home',
		'/contact': 'Contact'

This means that we'll then need both a Home and Contact component. Inside each component, I'm also adding a <router-link> which allows us to specify a to attribute, this navigates the user to that particular route.

Moon.component('Home', {
	template: `<div>
      <h1>Home Component</h1>
      <router-link to="/contact">Go Contact</router-link>

Moon.component('Contact', {
	template: `<div>
      <h1>Contact Component</h1>
      <router-link to="/">Go Home</router-link>

Finally, we need to tell Moon about our router instance. Let's do that with a new Moon instance:

const app = new Moon({
	el: '#app',