在Vue中使用MQTT实现通信过程
更新时间:2025年07月30日 09:31:15 作者:s_Myint
文章介绍了在Vue项目中集成MQTT的步骤:安装mqtt.js库,创建MQTT连接工具类以实现复用,通过Vue组件或直接在页面使用MQTT客户端,最后强调这是个人经验分享,鼓励支持脚本之家
一、安装 MQTT 客户端库
我们使用 mqtt.js,它是一个支持浏览器环境的 MQTT 客户端库。
通过以下命令安装:
npm install mqtt
二、创建 MQTT 连接工具类
为了方便管理和复用 MQTT 客户端,我们创建一个工具类 mqttClient.js,放在 src/utils 目录下:
import mqtt from 'mqtt';
class MQTTClient {
constructor(options) {
this.client = null;
this.messages = [];
this.subscribers = {};
this.defaultOptions = {
clientId: 'vue-client_' + Math.random().toString(16).substr(2, 8),
clean: true,
connectTimeout: 4000,
//username: '账号',
//password: '密码'
};
this.options = { ...this.defaultOptions, ...options };
}
connect(brokerUrl) {
return new Promise((resolve, reject) => {
try {
this.client = mqtt.connect(brokerUrl, this.options);
this.client.on('connect', () => {
console.log('连接成功');
resolve(this.client);
});
this.client.on('error', (err) => {
console.error('连接失败:', err);
reject(err);
});
this.client.on('message', (topic, payload) => {
const message = {
topic: topic,
content: payload.toString()
};
this.messages.push(message);
// 如果有订阅者,通知所有订阅了该主题的回调
if (this.subscribers[topic]) {
this.subscribers[topic].forEach(callback => callback(message));
}
});
this.client.on('close', () => {
console.log('MQTT connection closed');
});
} catch (err) {
reject(err);
}
});
}
// 订阅主题
subscribe(topic, callback, qos = 0) {
if (!this.client || this.client.connected === false) {
// console.error('MQTT not connected');
return;
}
this.client.subscribe(topic, { qos }, (err) => {
if (!err) {
console.log(`Subscribed to ${topic}`);
// 存储订阅回调
if (!this.subscribers[topic]) {
this.subscribers[topic] = [];
}
this.subscribers[topic].push(callback);
}
});
}
// 取消订阅指定主题的方法
unsubscribe(topic) {
if (!this.client || this.client.connected === false) {
console.error('MQTT not connected');
return;
}
this.client.unsubscribe(topic, (err) => {
if (!err) {
console.log(`Unsubscribed from ${topic}`);
// 移除订阅回调
if (this.subscribers[topic]) {
delete this.subscribers[topic];
}
}
});
}
// 发送消息
publish(topic, message, qos = 0, retain = false) {
if (!this.client || this.client.connected === false) {
console.error('MQTT not connected');
return;
}
this.client.publish(topic, message, { qos, retain }, (err) => {
if (err) {
console.error('Publish error:', err);
}
});
}
// 取消连接
disconnect() {
if (this.client) {
this.client.end();
this.client = null;
}
}
getMessages() {
return [...this.messages];
}
clearMessages() {
this.messages = [];
}
}
export default MQTTClient;
三、在 Vue 组件中使用
我们创建一个 Vue 组件来使用 MQTT 客户端
<template>
<div>
<h3>接收的 MQTT 消息:</h3>
<ul>
<li v-for="(msg, index) in messages" :key="index">
{{ msg.topic }}: {{ msg.content }}
</li>
</ul>
<!-- <ul>
<li v-for="(msg, index) in top2" :key="index">
{{ msg.topic }}: {{ msg.content }}
</li>
</ul> -->
<button @click="publishMessage">发送消息</button>
</div>
</template>
<script>
import MQTTClient from '@/util/mqtt';
export default {
data() {
return {
mqttClient: null,
messages: [],
top2:[]
};
},
mounted() {
this.initMQTT();
},
methods: {
initMQTT() {
this.mqttClient = new MQTTClient();
// 连接到 MQTT 代理
const url="ws://"+"你的地址"+":8083/mqtt" //例如ws://172.18.14.167:8083/mqtt
this.mqttClient.connect(url)
.then(() => {
console.log('订阅成功');
// 订阅主题
this.mqttClient.subscribe('kpmqqt-lims-data-top1', (message) => {
this.messages.push(message);
});
// this.mqttClient.subscribe('kpmqqt-lims-data-top2', (message) => {
// this.top2.push(message);
// });
})
.catch(err => {
console.error('MQTT connection failed:', err);
});
},
publishMessage() {
if (this.mqttClient) {
this.mqttClient.publish('kpmqqt-lims-data-top1', 'Hello from 测试Vue2!');
// this.mqttClient.publish('kpmqqt-lims-data-top2', 'Hello from 测试!');
} else {
console.error('MQTT client not initialized');
}
}
},
beforeDestroy() {
if (this.mqttClient) {
this.mqttClient.disconnect();
}
}
};
</script>
四、或者直接在页面使用
<template>
<div>
<h3>接收的 MQTT 消息:</h3>
<ul>
<li v-for="(msg, index) in messages" :key="index">
{{ msg.topic }}: {{ msg.content }}
</li>
</ul>
</div>
</template>
<script>
import mqtt from 'mqtt';
export default {
data() {
return {
client: null,
messages: []
};
},
mounted() {
this.initMQTT();
},
methods: {
initMQTT() {
const options = {
clientId: 'vue-client_' + Math.random().toString(16).substr(2, 8),
clean: true,
connectTimeout: 4000
};
const url="ws://"+"你的地址"+":8083/mqtt" //例如ws://172.18.14.167:8083/mqtt
this.client = mqtt.connect(url, options);
this.client.on('connect', (e) => {
this.subscribeTopics();
});
this.client.on('message', (topic, payload) => {
this.messages.push({
topic: topic,
content: payload.toString()
});
});
},
subscribeTopics() {
this.client.subscribe(['sensor/#'], { qos: 1 });
}
},
beforeDestroy() {
if (this.client) {
this.client.end();
}
}
};
</script>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章
vue-router启用history模式下的开发及非根目录部署方法
这篇文章主要介绍了vue-router启用history模式下的开发及非根目录部署方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-12-12
在 Vue 项目中引入 tinymce 富文本编辑器的完整代码
这篇文章主要介绍了在 Vue 项目中引入 tinymce 富文本编辑器的实例代码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下2018-05-05
elementui中el-row的el-col排列混乱问题及解决
这篇文章主要介绍了elementui中el-row的el-col排列混乱问题及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-08-08
Vue2+Element-ui实现el-table表格自适应高度的案例
这篇文章主要介绍了Vue2+Element-ui实现el-table表格自适应高度的案例,本文结合示例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧2024-06-06
elementui源码学习之仿写一个el-divider组件
这篇文章主要为大家介绍了elementui源码学习之仿写一个el-divider组件示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-08-08
解决ant-design-vue中menu菜单无法默认展开的问题
这篇文章主要介绍了解决ant-design-vue中menu菜单无法默认展开的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-10-10


最新评论