You've successfully subscribed to developer.school
Great! Next, complete checkout for full access to developer.school
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Using the MoonRouter with Moon.js

Paul Halliday
Paul Halliday

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

👋 Want to see more content? Head over to the YouTube channel: https://youtube.com/c/paulhalliday!