vue 链接mqtt

702 阅读1分钟

大家可能会遇到在vue里面调用mqtt的问题,所以我在这里给大家总结一下,一般这几个方法也就够用了。希望能帮助大家。

1.安装依赖

npm install mqtt --save

2.实例

<template>
    <div></div>
</template>
<script>
import mqtt from "mqtt";
export default {
  name: "Name",
  data() {
    return {
      connection: {
        host: "",//链接地址
        port: ,//端口
        endpoint: "/mqtt",
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        // 认证信息
        clientId: "mqttjs_3be2c321" + new Date().getTime(),
        username: "",//用户名 不用的话什么也不用填
        password: "",//密码 不用的话什么也不用填
      },
      subscription: {
        topic: "/devices/id_test/events",
        qos: 0,
      },
      receiveNews: "",
      client: {
        connected: false,
      },
      subscribeSuccess: false,
    };
  },
  created() { },
  mounted() {
    this.createConnection();
  },
  methods: {
    createConnection() {
      // 连接字符串, 通过协议指定使用的连接方式
      // ws 未加密 WebSocket 连接
      // wss 加密 WebSocket 连接
      // mqtt 未加密 TCP 连接
      // mqtts 加密 TCP 连接
      // wxs 微信小程序连接
      // alis 支付宝小程序连接
      const { host, port, endpoint, ...options } = this.connection;
      const connectUrl = `ws://${host}:${port}${endpoint}`;
      const { topic, qos } = this.subscription;
      try {
        this.client = mqtt.connect(connectUrl, options);
      } catch (error) {
        console.log("mqtt.connect error", error);
      }
      //连接mqtt
      this.client.on("connect", () => {
        console.log("Connection succeeded!");
        //订阅
        this.client.subscribe(topic, qos, (error, res) => {
          if (error) {
            console.log("subscribe to topics error", error);
            return;
          }
          this.subscribeSuccess = true;
          console.log("Subscribe to topics res", res);
        });
      });
      this.client.on("error", (error) => {
        console.log("Connection failed", error);
      });
      //获取消息
      this.client.on("message", (topic, message) => {
      });
      //下发 两个参数,一个是定义的topic另一个是你需要下发的内容
      this.client.publish('topic',content)
    },
  },
  destroyed() { },
};
</script>