// 引入 Vue 3 和 MQTT 库
import { createApp } from 'vue';
import mqtt from 'mqtt';
// 创建一个 Vue 应用实例
const app = createApp({
data() {
return {
message: '',
client: null,
isConnected: false
};
},
methods: {
// 连接到 MQTT 服务器
connect() {
const brokerUrl = 'ws://broker.hivemq.com:8000/mqtt'; // 替换为你的 MQTT 服务器地址
this.client = mqtt.connect(brokerUrl);
this.client.on('connect', () => {
console.log('Connected to MQTT broker');
this.isConnected = true;
this.client.subscribe('test/topic'); // 订阅主题
});
this.client.on('message', (topic, payload) => {
console.log(`Received message on topic ${topic}: ${payload.toString()}`);
this.message = `Received message on topic ${topic}: ${payload.toString()}`;
});
this.client.on('error', (error) => {
console.error('Connection error:', error);
this.isConnected = false;
});
},
// 发布消息到指定主题
publishMessage() {
if (this.isConnected && this.client) {
const topic = 'test/topic'; // 替换为你想要发布消息的主题
const message = 'Hello MQTT!';
this.client.publish(topic, message);
console.log(`Published message on topic ${topic}: ${message}`);
}
}
},
mounted() {
this.connect(); // 在组件挂载时连接到 MQTT 服务器
}
});
// 挂载应用到 DOM 中
app.mount('#app');
createApp 方法创建一个新的 Vue 应用实例,并定义了一些初始数据属性。methods 中定义了一个 connect 方法,用于连接到 MQTT 服务器。该方法使用 mqtt.connect 函数连接到指定的 MQTT 代理(Broker),并监听连接成功、接收到消息和发生错误的事件。publishMessage 方法,用于向指定主题发布消息。#app 元素上。这个示例展示了如何在 Vue 3 中集成 MQTT,实现与 MQTT 服务器的连接、订阅主题以及发布消息的功能。
下一篇:vue关闭eslint
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站