vue实现mqtt收发
Vue 中实现 MQTT 收发
安装 MQTT 客户端库
使用 mqtt 库或 paho-mqtt 实现连接。推荐 mqtt,兼容性更好:
npm install mqtt --save
创建 MQTT 连接
在 Vue 组件中初始化 MQTT 客户端并连接服务器:

import mqtt from 'mqtt';
export default {
data() {
return {
mqttClient: null,
receivedMessages: []
};
},
mounted() {
this.connectMqtt();
},
methods: {
connectMqtt() {
const options = {
clean: true,
connectTimeout: 4000,
clientId: 'vue-client-' + Math.random().toString(16).substr(2, 8)
};
this.mqttClient = mqtt.connect('ws://your-mqtt-broker:8083/mqtt', options);
this.mqttClient.on('connect', () => {
console.log('MQTT Connected');
this.subscribeToTopic('your/topic');
});
this.mqttClient.on('message', (topic, message) => {
this.receivedMessages.push({ topic, message: message.toString() });
});
this.mqttClient.on('error', (error) => {
console.error('MQTT Error:', error);
});
},
subscribeToTopic(topic) {
if (this.mqttClient) {
this.mqttClient.subscribe(topic, { qos: 0 }, (err) => {
if (!err) console.log(`Subscribed to ${topic}`);
});
}
}
}
};
发送 MQTT 消息
通过客户端实例的 publish 方法发送消息:

methods: {
sendMessage(topic, message) {
if (this.mqttClient) {
this.mqttClient.publish(topic, message, { qos: 0 }, (err) => {
if (!err) console.log(`Message sent to ${topic}`);
});
}
}
}
断开连接
组件销毁时主动断开连接:
beforeDestroy() {
if (this.mqttClient) {
this.mqttClient.end();
console.log('MQTT Disconnected');
}
}
安全配置
若需认证,在连接选项中添加凭据:
const options = {
username: 'your_username',
password: 'your_password',
// 其他配置...
};
注意事项
- WebSocket 地址需替换为实际 MQTT 代理地址(如
ws://test.mosquitto.org:8080) - QoS 级别根据需求调整(0/1/2)
- 生产环境建议使用 TLS 加密(
wss://) - 大流量场景需考虑消息队列优化






