使用前先下载相应的依赖包

npm install mqtt -S

一、单个订阅方式

1、在utils里面创建mqtt.js


import * as mqtt from "mqtt/dist/mqtt.min"; 
import { mqttUrl } from "../config/env"
class MQTT {
  url = '';// mqtt地址
  topic = ''; //订阅地址
  client ='';
  constructor(topic) {
    this.topic = topic;
    // 虽然是mqtt但是在客户端这里必须采用websock的链接方式
    this.url = mqttUrl;
  }

  //初始化mqtt
  init() {
    const options = {
      clean: true,
      connectTimeout: 4000, // 超时时间
    };
    this.client = mqtt.connect(this.url, options);
    this.client.on('error', (error) => {
      console.log(error);
    });
    this.client.on('reconnect', (error) => {
      console.log('正在重连:', error)
    });
  }
  //取消订阅
  unsubscribes() {
    this.client.unsubscribe(this.topic, (error) => {
      if (!error) {
        // console.log(this.topic, '取消订阅成功');
      } else {
        // console.log(this.topic, '取消订阅失败');
      }
    });
  }
  //连接
  link() {
    this.client.on('connect', (con) => {
      this.client.subscribe(this.topic, (error,res) => {
        if (!error) {
          console.log('订阅成功');
          console.log('主题', this.topic)
        } else {
          console.log('订阅失败');
        }
      });
    });
  }
  //收到的消息
  get(callback) {
    this.client.on('message', callback);
  }
  //结束链接
  over() {
    this.client.end();
  }
}
export default MQTT;

2.在utils里面创建useMqtt.js

import MQTT  from './mqtt';
import { onUnmounted, ref } from 'vue';

export default function useMqtt() {
  const PublicMqtt = ref(null);

  const startMqtt = (val, callback) => {
    //设置订阅地址
    PublicMqtt.value = new MQTT(val);
    //初始化mqtt
    PublicMqtt.value.init();
    //链接mqtt
    PublicMqtt.value.link();
    getMessage(callback);
  };
  const getMessage = (callback) => {
    PublicMqtt.value?.get(callback);
  };
  onUnmounted(() => {
    //页面销毁结束订阅
    if (PublicMqtt.value) {
      PublicMqtt.value.unsubscribes();
      PublicMqtt.value.over();
    }
  });

  return {
    startMqtt,
  };
}

3.使用

// 使用
import useMqtt from '@/utils/useMqtt'

 const { startMqtt } = useMqtt();
 startMqtt('主题topic', (topic, message) => {
    const msg = JSON.parse(message.toString());
    console.log(msg);
 });
//示例
 startMqtt('instructionMessageType/#', (topic, message) => {
  console.log(`来自:${topic}的消息:${JSON.parse(message)}`)
  const msg = JSON.parse(message.toString());
  if (msg.taskId == taskId.value) {
    switch (topic) {
      //撤退指令消息推送主题
      // case 'instructionMessageType/retreat'+'/'+taskId.value:
      //   console.log(msg, '1')
      //   console.log(instructList.value)
      //   instructList.value.retreatNum += 1;
      //   // instructList.value.executeNum -= 1;
      //   instructList.value.sendNum += 1;
      //   emitter.emit('instructListData', instructList.value)
      //   break;
        //指令中断消息推送主题
      case 'instructionMessageType/interrupt'+'/'+taskId.value:
        console.log(msg, '2')
        // instructList.value.retreatNum += 1;
        // instructList.value.executeNum -= 1;
        // instructList.value.sendNum -= 1;
        // instructList.value.stopNum += 1;
        // emitter.emit('instructListData', instructList.value)
        break;
    }
  }
})

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐