Connecting Nuxt.js to MQTT
In this blog post I’ll talk about how to connect Nuxt.js to MQTT.
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.
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.
Then simply install the dependencies.
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
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.
Make sure to replace the uri with your MQTT broker address.
Also, add the section below in the end of nuxt.config.js
.
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:
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:
To subscribe:
Don’t forget to run npm run dev to see the result.
You can see a completed example in here.
Originally published at https://imantabrizian.me/blog/nuxt-mqtt/.