vue中使用mqtt

参考地址: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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值