vue界面实现mqtt
Vue 实现 MQTT 通信
安装 MQTT 客户端库
在 Vue 项目中安装 mqtt 库:
npm install mqtt --save
创建 MQTT 连接
在 Vue 组件中引入 mqtt 并建立连接:
import mqtt from 'mqtt'
export default {
data() {
return {
client: null,
message: ''
}
},
mounted() {
this.connectMqtt()
},
methods: {
connectMqtt() {
const options = {
clean: true,
connectTimeout: 4000,
clientId: 'vue-client-' + Math.random().toString(16).substr(2, 8)
}
this.client = mqtt.connect('ws://mqtt.eclipseprojects.io:80/mqtt', options)
this.client.on('connect', () => {
console.log('Connected to MQTT broker')
this.client.subscribe('vue/demo')
})
this.client.on('message', (topic, payload) => {
this.message = payload.toString()
})
this.client.on('error', (error) => {
console.error('MQTT error:', error)
})
}
},
beforeDestroy() {
if (this.client) {
this.client.end()
}
}
}
发布消息
添加发布消息的方法:
methods: {
publishMessage() {
if (this.client && this.client.connected) {
this.client.publish('vue/demo', 'Hello from Vue')
}
}
}
模板部分
在模板中添加交互元素:

<template>
<div>
<button @click="publishMessage">发送消息</button>
<p>接收到的消息: {{ message }}</p>
</div>
</template>
安全配置
生产环境应考虑安全配置:
const options = {
username: 'your-username',
password: 'your-password',
reconnectPeriod: 1000
}
断线重连
添加断线重连逻辑:

this.client.on('close', () => {
console.log('Connection closed, attempting to reconnect...')
setTimeout(this.connectMqtt, 5000)
})
主题管理
实现动态主题订阅:
subscribeToTopic(topic) {
if (this.client && this.client.connected) {
this.client.subscribe(topic, { qos: 1 })
}
}
unsubscribeFromTopic(topic) {
if (this.client && this.client.connected) {
this.client.unsubscribe(topic)
}
}
QoS 设置
设置消息质量等级:
this.client.publish('vue/demo', 'Important message', { qos: 2 })
保留消息
发送保留消息:
this.client.publish('vue/demo', 'Retained message', { retain: true })






