在Vue3項目中使用MQTT獲取數(shù)據(jù)的方法示例
在 Vue 3 項目中使用 MQTT 獲取數(shù)據(jù),需通過 MQTT.js 庫實現(xiàn)與 MQTT 服務(wù)器的連接、訂閱主題及消息處理。以下是分步指南:
一、初始化 Vue 3 項目
使用 Vue CLI 或 Vite 創(chuàng)建項目:
npm create vue@latest # 使用 Vue CLI # 或 npm create vite@latest my-vue3-mqtt -- --template vue
二、安裝 MQTT.js 庫
通過 npm 或 yarn 安裝:
npm install mqtt # 或 yarn add mqtt
三、集成 MQTT 到 Vue 3 組件
1. 創(chuàng)建 MQTT 連接
在組件中引入 mqtt 并建立連接:
javascript
1import { onMounted, onBeforeUnmount, ref } from 'vue';
2import mqtt from 'mqtt';
3
4export default {
5 setup() {
6 const client = ref(null);
7 const messages = ref([]);
8
9 const connectMqtt = () => {
10 const options = {
11 keepalive: 30,
12 clientId: `vue3_${Math.random().toString(16).slice(2)}`,
13 username: 'your_username', // 可選
14 password: 'your_password', // 可選
15 clean: true,
16 };
17
18 // 使用 WebSocket 協(xié)議(ws:// 或 wss://)
19 client.value = mqtt.connect('ws://your_mqtt_server:8083/mqtt', options);
20
21 client.value.on('connect', () => {
22 console.log('Connected to MQTT Broker');
23 // 訂閱主題
24 client.value.subscribe('test/topic', { qos: 1 }, (err) => {
25 if (!err) console.log('Subscription successful');
26 });
27 });
28
29 client.value.on('message', (topic, message) => {
30 const data = JSON.parse(message.toString());
31 messages.value.push({ topic, data });
32 console.log(`Received: ${message.toString()} from ${topic}`);
33 });
34
35 client.value.on('error', (err) => {
36 console.error('MQTT Error:', err);
37 });
38
39 client.value.on('reconnect', () => {
40 console.log('Reconnecting...');
41 });
42
43 client.value.on('close', () => {
44 console.log('Disconnected from MQTT Broker');
45 });
46 };
47
48 onMounted(() => {
49 connectMqtt();
50 });
51
52 onBeforeUnmount(() => {
53 if (client.value) {
54 client.value.end();
55 }
56 });
57
58 return { messages };
59 }
60};
2. 發(fā)送消息(可選)
若需發(fā)布消息,可添加方法:
const publishMessage = (topic, payload) => {
2 if (client.value) {
3 client.value.publish(topic, JSON.stringify(payload), { qos: 1 }, (err) => {
4 if (err) console.error('Publish failed:', err);
5 else console.log('Message published');
6 });
7 }
8};
四、模板中顯示消息
在組件模板中渲染接收到的消息:
<template>
2 <div>
3 <h2>MQTT Messages</h2>
4 <ul>
5 <li v-for="(msg, index) in messages" :key="index">
6 <strong>{{ msg.topic }}:</strong> {{ msg.data }}
7 </li>
8 </ul>
9 </div>
10</template>
五、關(guān)鍵配置說明
連接協(xié)議:
- 瀏覽器端必須使用
ws://(非加密)或wss://(加密)協(xié)議。 - 端口通常為
8083(ws)或8084(wss),需與服務(wù)器配置一致。
QoS 等級:
0:至多一次(可能丟失)。1:至少一次(可能重復(fù))。2:只有一次(確保到達(dá))。
斷線重連:
- MQTT.js 默認(rèn)自動重連,可通過
reconnectPeriod調(diào)整重試間隔(毫秒)。
安全認(rèn)證:
- 若服務(wù)器啟用認(rèn)證,需在
options中配置username和password。
六、完整示例代碼
<script setup>
2import { ref, onMounted, onBeforeUnmount } from 'vue';
3import mqtt from 'mqtt';
4
5const client = ref(null);
6const messages = ref([]);
7
8const connectMqtt = () => {
9 const options = {
10 keepalive: 30,
11 clientId: `vue3_${Math.random().toString(16).slice(2)}`,
12 clean: true,
13 };
14
15 client.value = mqtt.connect('ws://your_mqtt_server:8083/mqtt', options);
16
17 client.value.on('connect', () => {
18 console.log('Connected');
19 client.value.subscribe('test/topic', { qos: 1 }, (err) => {
20 if (!err) console.log('Subscribed');
21 });
22 });
23
24 client.value.on('message', (topic, message) => {
25 messages.value.push({ topic, data: JSON.parse(message.toString()) });
26 });
27
28 client.value.on('error', (err) => {
29 console.error('Error:', err);
30 });
31};
32
33onMounted(() => {
34 connectMqtt();
35});
36
37onBeforeUnmount(() => {
38 if (client.value) client.value.end();
39});
40</script>
41
42<template>
43 <div>
44 <h2>MQTT Messages</h2>
45 <ul>
46 <li v-for="(msg, index) in messages" :key="index">
47 <strong>{{ msg.topic }}:</strong> {{ msg.data }}
48 </li>
49 </ul>
50 </div>
51</template>
七、常見問題解決
連接失敗:
- 檢查服務(wù)器地址是否為
ws://或wss://。 - 確認(rèn)端口和路徑(如
/mqtt)是否正確。
消息亂碼:
- 使用
message.toString()轉(zhuǎn)換Uint8Array為字符串。
跨域問題:
- 若服務(wù)器未配置 CORS,需通過代理或修改服務(wù)器配置解決。
性能優(yōu)化:
- 高頻消息時,使用防抖或節(jié)流減少渲染次數(shù)。
- 合并消息或使用 QoS 0 降低開銷。
以上就是在Vue3項目中使用MQTT獲取數(shù)據(jù)的方法示例的詳細(xì)內(nèi)容,更多關(guān)于Vue3 MQTT獲取數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用elementuiadmin去掉默認(rèn)mock權(quán)限控制的設(shè)置
這篇文章主要介紹了使用elementuiadmin去掉默認(rèn)mock權(quán)限控制的設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
Vue2?Dialog彈窗函數(shù)式調(diào)用實踐示例
這篇文章主要為大家介紹了Vue2?Dialog彈窗函數(shù)式調(diào)用實踐示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
vuex實現(xiàn)數(shù)據(jù)持久化的兩種方案
這兩天在做vue項目存儲個人信息的時候,遇到了頁面刷新后個人信息數(shù)據(jù)丟失的問題,在查閱資料后,我得出兩種解決數(shù)據(jù)丟失,使用數(shù)據(jù)持久化的方法,感興趣的小伙伴跟著小編一起來看看吧2023-08-08

