1.安装mqtt插件
npm install mqtt --save
2.打开所给地址,将代码下载到本地
https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js
3.引入。
import "./mqttws31.min";
4.函数中调用
created() {
// 连接服务器并注册连接成功处理事件
this.clientMqtt = this.client();
this.clientMqtt.connect(this.options());
this.clientMqtt.onMessageArrived = this.onMessageArrived;
// 注册连接断开处理事件
this.clientMqtt.onConnectionLost = this.onConnectionLost;
},
methods: {
client: function () {
// 下面参数都是后端给定的
return new Paho.MQTT.Client(this.hostname, this.port, this.clientId);
},
// mqtt配置项
options: function () {
let options = {
invocationContext: {
host: this.hostname,
port: this.port,
path: this.clientMqtt.path,
clientId: this.clientId,
},
timeout: 5000,
keepAliveInterval: 20,
cleanSession: false,
useSSL: false,
userName: "demo", //任意名字即可
password: this.token, //登录后获取的token值
onSuccess: this.onConnect,
onFailure: function (e) {
console.log(e);
},
};
return options;
},
// mqtt连接成功
onConnect: function () {
console.log("onConnected");
},
// mqtt接收消息
onMessageArrived(message) {
let messageJSON = JSON.parse(message.payloadString);
if (this.clientid == messageJSON.sendRegId) {
this.msgchild.saveMsgMap(
messageJSON.vContent,
messageJSON.sendRegId,
false,
messageJSON
);
} else {
for (var j = 0; j < this.chatList.length; j++) {
let clientId = this.chatList[j].clientId;
if (clientId == messageJSON.sendRegId) {
this.chatList[j].readCount += 1;
break;
}
}
this.PushMsgMap(
messageJSON.vContent,
messageJSON.sendRegId,
false,
messageJSON
);
}
this.chatList = this.chatList.sort(this.msgchild.sortTime("readCount"));
this.onScroll();
},
// mqtt断开事件
onConnectionLost: function (responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
console.log("连接已断开");
}
}
}