vue实现mqtt收发
Vue 中实现 MQTT 通信
安装 MQTT 客户端库
在 Vue 项目中安装 mqtt 库,支持浏览器和 Node.js 环境:
npm install mqtt --save
连接 MQTT 服务器
在 Vue 组件中引入并创建 MQTT 客户端:

import mqtt from 'mqtt';
const client = mqtt.connect('ws://mqtt.eclipse.org:80/mqtt');
订阅主题
连接成功后订阅指定主题:
client.on('connect', () => {
client.subscribe('topic/test', (err) => {
if (!err) console.log('订阅成功');
});
});
接收消息
监听 message 事件处理接收到的消息:

client.on('message', (topic, message) => {
console.log(`收到主题 ${topic} 的消息: ${message.toString()}`);
// 可更新 Vue 的 data 或触发方法
});
发送消息
通过 publish 方法发送消息:
methods: {
sendMessage() {
client.publish('topic/test', 'Hello MQTT');
}
}
断开连接
组件销毁时关闭连接:
beforeDestroy() {
client.end();
}
完整组件示例
<template>
<div>
<button @click="sendMessage">发送消息</button>
<div>接收消息: {{ receivedMsg }}</div>
</div>
</template>
<script>
import mqtt from 'mqtt';
export default {
data() {
return {
client: null,
receivedMsg: ''
};
},
mounted() {
this.client = mqtt.connect('ws://mqtt.eclipse.org:80/mqtt');
this.client.on('connect', () => {
this.client.subscribe('topic/test');
});
this.client.on('message', (topic, message) => {
this.receivedMsg = message.toString();
});
},
methods: {
sendMessage() {
this.client.publish('topic/test', 'Hello from Vue');
}
},
beforeDestroy() {
this.client.end();
}
};
</script>
注意事项
- 生产环境建议使用加密连接
wss:// - 可配置用户名密码:
mqtt.connect('ws://host', { username: 'user', password: 'pass' }) - 错误处理需监听
error事件 - 支持 QoS 等高级参数配置






