Vue使用mqtt插件

1 篇文章 0 订阅

1. 下载插件

npm install mqtt

2. 注册插件 main.js(可不用)

import mqtt from "mqtt";
Vue.prototype.$mqtt = mqtt;

3. 设计存放mqtt配置的js

import mqtt from "mqtt";
/*
使用方法
this.client= new initMqtt().connect()
*/

function initMqtt(options) {
  const {
    hostname,
    port,
    timeout,
    keepAlive,
    cleanSession,
    ssl,
    userName,
    password,
    path
  } = options || {};
  this.hostname = hostname || "192.168.10.65";
  this.port = port || 9001;
  this.options = {
    // clean: true, // 保留会话
    connectTimeout: 4000, // 超时时间
    reconnectPeriod: 4000, // 重连时间间隔
    clientId: "41215676e5cf4e638a3fae8c5cf38024",
    username: userName || "admin",
    password: password || "123456",
  };
  this.connectUrl = `ws://${this.hostname}:${this.port}`;
}

initMqtt.prototype.connect = function(onSuccess, onLost, onMessageArrival) {
  try {
    this.client = mqtt.connect(this.connectUrl, this.options);
  } catch (error) {
    console.log("mqtt.connect error", error);
  }
  this.client.on("connect", () => onSuccess());
  this.client.on("error", error => onLost);
  this.client.on("message", (topic, message) => onMessageArrival(topic, message.toString()));
  return this.client;
};
initMqtt.prototype.disconnect = function() {
  if (this.client) {
     this.client = null;
  }
};

export default initMqtt;

4. 调用

<!--  -->
<template>
  <div>
    <button @click="publish">主题推送</button>
  </div>
</template>
<script>
import initMqtt from "../../utils/initMqtt";
export default {
  data() {
    return {};
  },
  props: [],
  components: {},
  created() {},
  mounted() {
    // console.log($mqtt)
    this.initmqtt = new initMqtt();
    this.client = this.initmqtt.connect(
      () => {
        console.log("链接成功,开始订阅主题");
        this.client.subscribe("home/garden/fountainss");
      },
      this.onConnectionLost,
      this.onMessageArrived
    );
  },
  methods: {
    onMessageArrived(a, b) {
      console.log("收到的数据", b);
    },
    onConnectionLost() {
      console.log("链接丢失");
    },
    publish() {
      this.client.publish("home/garden/fountainss", "我爱你");
    },
  },
  beforeDestroy() {
    // console.log(this.client.unsubscribe)
    this.client.unsubscribe("home/garden/fountainss")
    this.client = null;
  }
};
</script>
<style lang="scss" scoped></style>

效果

在这里插入图片描述
在这里插入图片描述

代码地址:点我进入

路由为 /mqttText

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值