Skip to content

Instantly share code, notes, and snippets.

@Tabrizian
Created November 18, 2017 19:47
Show Gist options
  • Save Tabrizian/afc4b6d593fe1e68c6ade677cea018cd to your computer and use it in GitHub Desktop.
Save Tabrizian/afc4b6d593fe1e68c6ade677cea018cd to your computer and use it in GitHub Desktop.

In this blog post I'll talk about how to connect Nuxt.js to MQTT.

Introduction

MQTT has become the de facto of IoT. According to the statistics after HTTP it is the most used protocol for the connectivity layer of IoT devices. In this blog post you'll learn how to combine this amazing protocol with Nuxt.js.

Getting Started

Prerequisites

This tutorial assumes that you already know what is Vue.js. If don't you can read about it here.

Installing Nuxt.js

First install Nuxt.js:

As stated in the docs installing is pretty simple.

https://gist.github.com/51e705a721813efe0216ebc627cc23d1

Then simply install the dependencies.

https://gist.github.com/9b4112320e2be8a5f712425e847d29ee

https://gist.github.com/559a811308e0edf2065b229d61d0b875

Now you should be able to view the the site on http://localhost:3000.

Nuxt plugins

Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root vue.js application. This is especially helpful when using your own libraries or external modules. Nuxtjs.org

For more information about Nuxt.js plugins you can read about here.

So lets use it!

Add required dependencies

https://gist.github.com/754e1609efdec5d09b48facc71d4eb7f

This is a vue plugin that registers mqtt on Vue instance globally we'll see how to use it later.

Create a nuxt plugin

Create a new nuxt plugin by adding vue-mqttsocket plugin in plugins/mqtt.js .

In order to do so, put the following content in it.

https://gist.github.com/6786dbb734f72686893026f7ba8a0015

Make sure to replace the uri with your MQTT broker address.

Also, add the section below in the end of nuxt.config.js.

https://gist.github.com/306fee00de241e04c2c9d4f04657992d

This will register the plugin in the nuxt.

Usage

Now you can register it in everypage that you need MQTT in a very simple way. All you have to do is to put the code below in the mounted section of your page:

https://gist.github.com/04ff0b1d27fee79c519a8f7517044add

If you were successful you'll be able to see a MQTT connected! message in the log of your browser.

Now publishing and subscribing is super simple.

To publish:

https://gist.github.com/877100e4807598d538a70e9126f7eb51

To subscribe:

https://gist.github.com/2b5c2b12990cdb1fd070977eb3955eda

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment