npm install mqtt
或
<template> <div> <p></p> </div> </template> <script> import { uuid } from "vue-uuid"; export default { name: "MqttConnect", props: {}, data() { return { config: {}, reconnectTimeout: 2000, mqtt: null, msg: "", topic: "mqtt", // 订阅的主题 }; }, watch: {}, mounted() { this.config = { host: "192.168.1.10", port: 31800, addtopic: "get/test", useTLS: false, username: "redgex", password: "redgex", cleansession: false, }; this.MQTTconnect(this.config); }, methods: { MQTTconnect(config) { this.mqtt = new window.Paho.MQTT.Client( // 实例化一个对象 config.host, config.port, "client" + uuid.v1() // 防止多个浏览器打开,导致的问题,保证唯一性 ); var options = { timeout: 10, useSSL: config.useTLS, cleanSession: config.cleansession, // 如果为false(flag=0),Client断开连接后,Server应该保存Client的订阅信息。如果为true(flag=1),表示Server应该立刻丢弃任何会话状态信息。 onSuccess: this.onConnect, onFailure: function(message) { console.log(message); // 连接失败定时重连 setTimeout(this.MQTTconnect, this.reconnectTimeout); }, }; this.mqtt.onConnectionLost = this.onConnectionLost; // 注册连接断开处理事件 this.mqtt.onMessageArrived = this.onMessageArrived; // 注册消息接收处理事件 // 用户名和密码的验证,我这里都为空;不加验证 if (config.username != null) { options.userName = config.username; options.password = config.password; } this.mqtt.connect(options); // 连接服务器并注册连接成功处理事件 }, onConnectionLost: function(responseObject) { if (responseObject.errorCode !== 0) { console.log("onConnectionLost:" + responseObject.errorMessage); console.log("连接已断开"); } }, onMessageArrived: function(message) { this.$emit("postData", message); }, onConnect: function() { console.log("onConnected"); this.mqtt.subscribe(this.config.addtopic); // 订阅主题 // 发布一个消息,再连接成功后,发送一个响应,确保连接没有问题; // this.mqtt.send(‘login‘, ‘{"command":"login","clientId":"‘ + this.mqtt.clientId + ‘"}‘, 0); }, mqttHandleclick(status) { if (!status && this.mqtt) { this.mqtt.disconnect(); this.mqtt = null; } }, }, }; </script> <style> .apps { width: 100%; overflow: hidden; } </style>
原文:https://www.cnblogs.com/zigood/p/14722843.html