vue 使用 mqtt,以及vue3 + typescript 使用mqtt时的一些处理

npm install mqtt

vue3 使用 ts 后需要在 shims-vue.d.ts 里面进行声明下

declare module 'mqtt';

  

可以下载mqttx 进行模拟测试

<template>

</template>

<script>
import mqtt from "mqtt" export default { name: "MqttConnect", data(){ return { client: null, isReconnectMqtt: false } }, beforeDestroy() { if (this.client) { this.client.end(); } }, mounted() { this.connectMqtt(); }, methods: { handleMqttMessage(topic, message) { // 接收数据 console.log(message.toString()) // JSON.parse(message.toString()) }, connectMqtt() { const mqttConfig = { clientId: 'mqttx_7b8f9ec6', clean: true, reconnectPeriod: 1000, // 1000毫秒,两次重新连接之间的间隔 // connectTimeout: 30 * 1000, // 1000毫秒,两次重新连接之间的间隔 // resubscribe: true // 如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true) username: "admin", // 账户名密码没就不用写 password: "password", }; let mqtt_ws_url = "ws://127.0.0.1:1884" if (!this.client) { this.client = mqtt.connect(mqtt_ws_url, mqttConfig); } const topic = ["/test"] // 主题 const that = this;
          // 订阅主题 this.client.subscribe(type, function(err) { if (!err) { console.log("Hello mqtts"); that.client.publish('test', 'Hello mqtt') } else { console.log(err) } }) this.client.on('message', this.handleMqttMessage) this.client.on("connect", () =>{ if (this.isReconnectMqtt) { this.client.end(); this.connectMqtt(); this.isReconnectMqtt = false; } }); this.client.on('error', function(error) { console.log("error", error) }) this.client.on('close', function() { console.log('close Disconnected') }) this.client.on("reconnect", function() { this.isReconnectMqtt = true; console.log("mqtt client try to reconnect"); }); } } } </script>

  

posted @ 2022-05-31 11:21  越甲鸣吾君  阅读(1943)  评论(0编辑  收藏  举报