参考地址:https://blog.csdn.net/qq_39370934/article/details/107378126
学习一下,根据上述操作说明
1 执行命令
cnpm install mqtt@3.0.0 -S
2 代码
<script>
//引入mqtt
import mqtt from "mqtt";
//引入connect配置
//import { mqttConfig } from "../../commonParams/index.js"
export const mqttConfig = {
port: 8083,
// keepalive: 60,
// clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
// protocolId: 'MQTT',
// protocolVersion: 4,
// clean: true,
}
export default {
components: {},
data() {
return {
MQTT:"",
};
},
created() {},
mounted() {
var _this = this
// const _this = this;
//建立连接,需要搭建消息中间件服务器的(我这里是后台)提供用户名或密码
const cfg = Object.assign(mqttConfig, {
username: 'admin',
password: '123456',
});
// 在data中定义MQTT,以便断开连接
// ws://xxxxx是连接地址,后台提供,wss是https连接
_this.MQTT = mqtt.connect('ws://127.0.0.1/mqtt', cfg)
_this.MQTT.on('error', (e) => {
_this.MQTT.end();
});
//建立连接后订阅主题
_this.MQTT.on('connect', () => {
// 订阅一个主题:result_message
_this.MQTT.subscribe("result_message", { qos: 1 }, err => {
if (!err) {
console.info(' ---- 订阅成功')
} else {
console.warn('订阅失败')
}
})
});
// 后台发送的消息
_this.MQTT.on('message', function (top, message) {
//发送过来的如果是对象你是需要解析的。
const res = JSON.parse(message.toString());
const TOP = top.replace('tops/', '');
console.log(top + ': ', res);
//根据不同主题进行赋值操作
switch (TOP) {
case "top1":
_this.data1 = [res];
break;
case "top2":
_this.data2 = [...res];
break;
//其他情况
}
});
// 其他异常事件
_this.MQTT.on('reconnect', () => {
console.info('正在重连')
});
_this.MQTT.on('disconnect', (error) => {
console.info('服务器断开:', error)
});
_this.MQTT.on('close', () => {
_this.MQTT.end();
});
},
methods: {
},
beforeDestroy() {
//退出时关闭Mqtt
if(this.MQTT.end) {
this.MQTT.end();
}
}
};
</script>