vue连接mqtt实现收发消息组件超级详细
<template>
<div>
<button @click="connect">连接MQTT</button>
<button @click="disconnect">断开连接</button>
<button @click="publishMessage">发送消息</button>
<textarea v-model="message" placeholder="输入消息"></textarea>
<div v-for="item in logs" :key="item.id">{{ item.time }} - {{ item.message }}</div>
</div>
</template>
<script>
import mqtt from 'mqtt';
export default {
data() {
return {
client: null,
message: '',
logs: [],
};
},
methods: {
connect() {
this.client = mqtt.connect('mqtt://broker.hivemq.com');
this.client.on('connect', () => {
this.logs.push({ id: Date.now(), message: '连接成功', time: new Date().toLocaleTimeString() });
console.log('连接成功');
});
this.client.on('error', (error) => {
this.logs.push({ id: Date.now(), message: '连接发生错误', time: new Date().toLocaleTimeString() });
console.error('连接发生错误', error);
});
this.client.on('end', () => {
this.logs.push({ id: Date.now(), message: '连接已断开', time: new Date().toLocaleTimeString() });
console.log('连接已断开');
});
this.client.on('message', (topic, payload) => {
this.logs.push({ id: Date.now(), message: `收到消息: ${payload.toString()}`, time: new Date().toLocaleTimeString() });
console.log(`收到消息: ${payload.toString()}`);
});
},
disconnect() {
if (this.client) {
this.client.end();
}
},
publishMessage() {
if (this.client && this.message.length) {
this.client.publish('topic', this.message, { qos: 0, retain: false });
this.logs.push({ id: Date.now(), message: `发送消息: ${this.message}`, time: new Date().toLocaleTimeString() });
this.message = '';
}
}
}
};
</script>
这个代码实例展示了如何在Vue应用中使用mqtt包来连接MQTT服务器,并实现了连接、断开连接、发送消息和接收消息的功能。同时,它还包括了简单的日志记录功能,以便开发者可以查看消息的收发历史。这个例子是一个很好的教学资源,对于需要在Vue项目中集成MQTT通信的开发者来说
评论已关闭