您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2025/11/13 23:19:30发布12次查看
vue3+vite2+mqtt连接遇到的坑之前用vue2连接mqtt时是这样的方式 :
1.yarn add mqtt 或 npm install mqtt
2.import mqtt from 'mqtt'
安装完后直接在页面引用,就可以用了
所以在vue2项目里是比较简单的。
但是,但可是,可但是
移到vue3就遇到各种报错了,referenceerror: global is not defined
找遍整网也很难找到想关的答案。
于是就各种升降级改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('message', callback); // @ts-ignore //忽略提示 publicmqtt.value?.get(callback); };// onunmounted(() => {// //页面销毁结束订阅// if (publicmqtt.value) {// publicmqtt.value.unsubscribes();// publicmqtt.value.over();// }// }); return { startmqtt, };}
使用页面调用
import usemqtt from '@/utils/usemqtt';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 'mqtt' export default { data() { return { account:"12", password:"12", connection: { host: 'www.liufengtec.com', port: 8084, endpoint: '/mqtt', clean: true, // 保留会话 connecttimeout: 4000, // 超时时间 reconnectperiod: 4000, // 重连时间间隔 // 认证信息 clientid: 'mqttjs_3be2c321', username: 'admin', password: '3ha86294', }, subscription: { topic: 'topic/mqttx', qos: 0, }, publish: { topic: 'topic/browser', qos: 0, payload: '{ "msg": "hello, i am browser." }', }, receivenews: '', 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('mqtt.connect error', error) } this.client.on('connect', () => { console.log('connection succeeded!') that.subscribe(); }) this.client.on('error', error => { console.log('connection failed', error) }) this.client.on('message', (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连接遇到的坑怎么解决的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product