首页 > web前端 > Vue.js > 正文

vue3+vite2+mqtt连接遇到的坑怎么解决

王林
发布: 2023-05-10 19:22:04
转载
2352 人浏览过

vue3+vite2+mqtt连接遇到的坑

之前用vue2连接mqtt时是这样的方式 :

1.yarn add mqtt 或 npm install mqtt

2.import mqtt from 'mqtt'

安装完后直接在页面引用,就可以用了

所以在vue2项目里是比较简单的。

但是,但可是,可但是

移到vue3就遇到各种报错了,ReferenceError: global is not defined

找遍整网也很难找到想关的答案。

vue3+vite2+mqtt连接遇到的坑怎么解决

于是就各种升降级改MQTT版本,毛用。各种CDN引用,毛鸟用。

最后去node_modules目录看看,发现有个dist的目录,难道。。。

抱着试试的心态,就改为这样:

import * as mqtt from "mqtt/dist/mqtt.min"; 
that.client = mqtt.connect('ws://' + mqttOption.server, mqttOption);
登录后复制

我去,还真的是可以了!搞足了一天,终于搞定。

那种心情是无法言语的,或许这就是码农的快乐之一吧!

vue3调用mqtt问题

npm install mqtt -S
登录后复制

utils下面新建mqtt页面

import { MqttClient, OnMessageCallback } from 'mqtt';
import mqtt from 'mqtt';
 
class MQTT {
  url: string; // mqtt地址
  topic: string; //订阅地址
  client!: MqttClient;
  constructor(topic: string) {
    this.topic = topic;
    // 虽然是mqtt但是在客户端这里必须采用websock的链接方式
    this.url = 'ws://www.liufengtec.com:8083/mqtt';
  }
 
  //初始化mqtt
  init() {
    const options = {
        host: 'www.liufengtec.com',
        port: 8083,
        endpoint: '/mqtt',
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        // 认证信息
        clientId: 'mqttjs_3be2c321',
        username: 'admin',
        password: '3Ha86294',
    };
    this.client = mqtt.connect(this.url, options);
    this.client.on('error', (error: any) => {
      console.log(error);
    });
    this.client.on('reconnect', (error: Error) => {
      console.log(error);
    });
  }
  //取消订阅
  unsubscribes() {
    this.client.unsubscribe(this.topic, (error: Error) => {
      if (!error) {
        console.log(this.topic, '取消订阅成功');
      } else {
        console.log(this.topic, '取消订阅失败');
      }
    });
  }
  //连接
  link() {
    this.client.on('connect', () => {
      this.client.subscribe(this.topic, (error: any) => {
        if (!error) {
          console.log('订阅成功');
        } else {
          console.log('订阅失败');
        }
      });
    });
  }
  //收到的消息
  get(callback: OnMessageCallback) {
    this.client.on('message', callback);
    // console.log(callback,"1010")
  }
  //结束链接
  over() {
    this.client.end();
  }
}
export default MQTT;
登录后复制

utils下面新建usemqtt.ts页面

import MQTT from '@/utils/mqtt';
import { OnMessageCallback } from 'mqtt';
import { ref } from "vue";
 
export default function useMqtt() {
  const PublicMqtt = ref<MQTT | null>(null);
 
  const startMqtt = (val: string, callback: OnMessageCallback) => {
    //设置订阅地址
    PublicMqtt.value = new MQTT(val);
    //初始化mqtt
    PublicMqtt.value.init();
    //链接mqtt
    PublicMqtt.value.link();
    getMessage(callback);
  };
  const getMessage = (callback: OnMessageCallback) => {
    //   console.log(callback,"18")
    // PublicMqtt.value?.client.on(&#39;message&#39;, callback);
    // @ts-ignore //忽略提示
    PublicMqtt.value?.get(callback);
  };
//   onUnmounted(() => {
//     //页面销毁结束订阅
//     if (PublicMqtt.value) {
//       PublicMqtt.value.unsubscribes();
//       PublicMqtt.value.over();
//     }
//   });
 
  return {
    startMqtt,
  };
}
登录后复制

使用页面调用

import useMqtt from &#39;@/utils/usemqtt&#39;;
const { startMqtt } = useMqtt();
startMqtt(deviceSnsss, (topic, message) => {
console.log(message)
}
登录后复制

或者

<template>
  <div id="app">
    <div class="head">
      <p>天润商城后台管理系统</p>
    </div>
    <div class="login">
      <table border="0" cellspacing="20">
        <tr>
          <td>用户名:</td>
          <td>
            <el-input
              prefix-icon="iconfont icon-xingmingyonghumingnicheng"
              placeholder="请输入账号"
              v-model="account"
              clearable
            ></el-input>
          </td>
        </tr>
 
        <tr>
          <td>密码:</td>
          <td>
            <el-input
              prefix-icon="iconfont icon-mima"
              placeholder="请输入密码"
              v-model="password"
              show-password
            ></el-input>
          </td>
        </tr>
        <tr>
          <td colspan="2" >
            <el-button type="danger"  @click="login"
              >登录</el-button
            >
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
 
<script>
  import mqtt from &#39;mqtt&#39;
  
  export default {
    data() {
      return {
        account:"12",
        password:"12",
        connection: {
          host: &#39;www.liufengtec.com&#39;,
          port: 8084,
          endpoint: &#39;/mqtt&#39;,
          clean: true, // 保留会话
          connectTimeout: 4000, // 超时时间
          reconnectPeriod: 4000, // 重连时间间隔
          // 认证信息
          clientId: &#39;mqttjs_3be2c321&#39;,
          username: &#39;admin&#39;,
          password: &#39;3Ha86294&#39;,
        },
        subscription: {
          topic: &#39;topic/mqttx&#39;,
          qos: 0,
        },
        publish: {
          topic: &#39;topic/browser&#39;,
          qos: 0,
          payload: &#39;{ "msg": "Hello, I am browser." }&#39;,
        },
        receiveNews: &#39;&#39;,
        qosList: [
          { label: 0, value: 0 },
          { label: 1, value: 1 },
          { label: 2, value: 2 },
        ],
        client: {
          connected: false,
        },
        subscribeSuccess: false,
      }
    },
  
    methods: {
      login(){
         this.createConnection();
      },
      // 创建连接
      createConnection() {
        let that=this;
        // 连接字符串, 通过协议指定使用的连接方式
        // ws 未加密 WebSocket 连接
        // wss 加密 WebSocket 连接
        // mqtt 未加密 TCP 连接
        // mqtts 加密 TCP 连接
        // wxs 微信小程序连接
        // alis 支付宝小程序连接
        const { host, port, endpoint, ...options } = this.connection
        const connectUrl = `ws://www.liufengtec.com:8083/mqtt`
        try {
          this.client = mqtt.connect(connectUrl)
        } catch (error) {
          console.log(&#39;mqtt.connect error&#39;, error)
        }
        this.client.on(&#39;connect&#39;, () => {
          console.log(&#39;Connection succeeded!&#39;)
          that.subscribe();
          
        })
        this.client.on(&#39;error&#39;, error => {
          console.log(&#39;Connection failed&#39;, error)
        })
        this.client.on(&#39;message&#39;, (topic, message) => {
          this.receiveNews = this.receiveNews.concat(message)
          console.log(`Received message ${message} from topic ${topic}`)
        })
      },
      //订阅
   subscribe() {
    var topic = "system";
    var qos = 0;
    //logMessage("INFO", "Subscribing to: [Topic: ", topic, ", QoS: ", qos, "]");
    this.client.subscribe(topic, { qos: Number(qos) });
   },
   // called when a message arrives
    message() {
      var topic = "system";
   this.client.on("message", (topic, message) => {
      console.log(message)
    });
  }
 
 
    }
  }
  </script>
 
<style lang="less" scoped>
.head {
  height: 150px;
  width: 100vw;
  background-image: url(../assets/banner.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  p {
    font-size: 30px;
    color: white;
    line-height: 150px;
    margin-left: 50px;
  }
}
.bg-purple {
  background: #d3dce6;
}
 
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 400px;
  margin: 0px auto;
  border: 2px #f3f3f3 solid;
  padding: 100px;
}
</style>
登录后复制

不封装直接使用。ws和wss不一样

vue3+vite2+mqtt连接遇到的坑怎么解决

以上是vue3+vite2+mqtt连接遇到的坑怎么解决的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:yisu.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板