1、下载MQTT “npm install mqtt”
也可以直接将{"mqtt": "^4.2.6",}放到package.json中,然后执行npm install
2、emqx.js文件,引入mqtt,及相关事件
import MQTT from 'mqtt'
const mqttId = Math.random().toString(36).substr(2);
const topicList = {};
//username password 为连接的后台用户及密码
const option = {
clean: true,
connectTimeout: 4000,
clientId: mqttId,
username: 'admin',
password: '123456'
}
const connectUrl = 'ws://192.168.0.161:9999/mqtt';//此为连接的后台地址
const emqx = MQTT.connect(connectUrl, option);
emqx.on('connect', () => {
console.log('mqtt服务器连接成功', connectUrl);
}).on('error', (err) => [
console.log('MQTT连接失败,出现异常:', err)
]).on('message', (topic, payload) => {
let msgJson = JSON.parse(payload);
if(!topicList[topic]) return;
topicList[topic](msgJson);
})
emqx.subscribeTopic = function(topic, callback) {
if(typeof(topic) !== 'string' || typeof(callback) !== 'function') {
console.log('输入的话题或者回调函数格式不正确');
return;
}
emqx.subscribe(topic);
topicList[topic] = callback;
}
export {
emqx
}
3、页面中使用
import { emqx } from "@/api/emqx";
//message为后端定的各种事件名,前端订阅,进而获取对应的数据
emqx.subscribeTopic('message', data=> {
console.log(data,'后端传来的数据')
})