vue界面实现mqtt
实现Vue界面集成MQTT通信
安装MQTT客户端库
在Vue项目中安装mqtt库,通过npm或yarn执行安装命令:
npm install mqtt --save
# 或
yarn add mqtt
创建MQTT服务封装
新建src/utils/mqttClient.js文件,封装MQTT连接逻辑:

import mqtt from 'mqtt'
const options = {
clean: true,
connectTimeout: 4000,
clientId: 'vue_' + Math.random().toString(16).substr(2, 8)
}
let client = null
export function connectMQTT(brokerUrl) {
client = mqtt.connect(brokerUrl, options)
client.on('connect', () => {
console.log('MQTT connected')
})
client.on('error', (error) => {
console.error('MQTT error:', error)
})
return client
}
export function subscribe(topic) {
if (client) {
client.subscribe(topic, { qos: 0 }, (err) => {
if (!err) console.log(`Subscribed to ${topic}`)
})
}
}
export function publish(topic, message) {
if (client) {
client.publish(topic, message, { qos: 0 })
}
}
export function disconnect() {
if (client) {
client.end()
client = null
}
}
Vue组件中使用MQTT 在组件中导入并使用封装好的MQTT方法:
import { connectMQTT, subscribe, publish, disconnect } from '@/utils/mqttClient'
export default {
data() {
return {
receivedMessages: [],
inputTopic: '',
inputMessage: ''
}
},
mounted() {
connectMQTT('ws://broker.emqx.io:8083/mqtt')
subscribe('test/topic')
this.$mqtt = this.$root.$mqtt || {}
this.$mqtt.client = this.$root.$mqtt.client
this.$mqtt.client.on('message', (topic, message) => {
this.receivedMessages.push({
topic,
message: message.toString()
})
})
},
methods: {
sendMessage() {
publish(this.inputTopic, this.inputMessage)
this.inputMessage = ''
}
},
beforeDestroy() {
disconnect()
}
}
界面模板示例

<template>
<div>
<div>
<input v-model="inputTopic" placeholder="Enter topic">
<input v-model="inputMessage" placeholder="Enter message">
<button @click="sendMessage">Publish</button>
</div>
<div>
<h3>Received Messages:</h3>
<ul>
<li v-for="(msg, index) in receivedMessages" :key="index">
{{ msg.topic }}: {{ msg.message }}
</li>
</ul>
</div>
</div>
</template>
安全注意事项
- 生产环境应使用TLS加密连接(wss://)
- 避免在前端暴露敏感凭证,建议通过后端代理MQTT连接
- 设置合理的QoS级别根据业务需求
- 实现重连机制处理网络中断情况
性能优化建议
- 使用Vuex管理MQTT状态避免多组件重复连接
- 对高频消息进行节流处理
- 考虑使用WebWorker处理大量消息数据
- 实现主题通配符订阅时注意性能影响






