/ moon

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">
<head>
  <title>Moon.js Router</title>
</head>
<body>  
<script src="https://unpkg.com/moonjs/dist/moon.js"></script>
<script src="https://unpkg.com/moon-router"></script>

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

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">
<router-view></router-view>
</div>

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

Moon.use(MoonRouter);

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>
    </div>
  `
});

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

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',
    router
});

Components

Tada!

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More