您好,登錄后才能下訂單哦!
本篇內容主要講解“vue3怎么使用mqtt”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“vue3怎么使用mqtt”吧!
封裝類
//封裝一個類(可直接cv) class createds { //創建公共變量 static url; //mqtt地址 static oldSubscribe; //取消訂閱準備 static subscribe; //訂閱地址 static client; //mqtt公共變量 //接受床底來的數據 constructor(subscribe) { console.log(subscribe, "訂閱地址"); //獲取傳遞來的訂閱地址 this.subscribe = subscribe; this.url = "ws://127.0.0.1:8083/mqtt"; } //初始化mqtt init() { const options = { clean: true, // true: 清除會話, false: 保留會話 connectTimeout: 4000, // 超時時間 }; this.client = mqtt.connect(this.url, options); this.client.on("error", (error) => {}); this.client.on("reconnect", (error) => {}); } //取消訂閱 unsubscribes() { this.client.unsubscribe(this.subscribe, (error) => { if (!error) { console.log(this.subscribe, "取消訂閱成功"); } else { console.log(this.subscribe, "取消訂閱失敗"); } }); } //結束鏈接 over() { this.client.end(); } //鏈接 link() { this.client.on("connect", (e) => { this.client.subscribe(this.subscribe, (error) => { //在js代碼中最簡單的拋出異常方法 if (!error) { console.log("訂閱成功"); } else { console.log("訂閱失敗"); } }); }); } //收到的消息 get() { this.client.on("message", (topic, message) => { console.log("收到消息:", message.toString()); }); } //結束鏈接 over() { this.client.end(); } } export default createds;
使用
//引入封裝的類 import createds from "@/utils/mqtt.js"; const PublicMqtt = ref(null); const startMqtt = (val) => { //val = 訂閱地址 //設置訂閱地址 PublicMqtt.value = new createds(val); //初始化mqtt PublicMqtt.value.init(); //鏈接mqtt PublicMqtt.value.link(); getMessage(); }; //獲取訂閱數據 const getMessage = () => { PublicMqtt.value.client.on("message", (topic, message) => { let str = JSON.parse(message.toString()); console.log(str,'返回的數據') }); }; //取消MQTT訂閱 const unsubscribe = () => { //如果頁面并沒有初始化MQTT,無需取消訂閱 if (PublicMqtt.value) { PublicMqtt.unsubscribes(); } }; onUnmounted(() => { //頁面銷毀結束訂閱 if (PublicMqtt.value) { PublicMqtt.value.unsubscribes(); PublicMqtt.value.over(); } }); // vue3使用npm下載mqtt依賴可能跑不起來,可以把他的js文件下載下來放在本地
npm install mqtt -S
utils下面新建mqtt頁面
import { MqttClient, OnMessageCallback } from 'mqtt'; import mqtt from 'mqtt'; class MQTT { url: string; // mqtt地址 topic: string; //訂閱地址 client!: MqttClient; constructor(topic: string) { this.topic = topic; // 雖然是mqtt但是在客戶端這里必須采用websock的鏈接方式 this.url = 'ws://www.liufengtec.com:8083/mqtt'; } //初始化mqtt init() { const options = { host: 'www.liufengtec.com', port: 8083, endpoint: '/mqtt', clean: true, // 保留會話 connectTimeout: 4000, // 超時時間 reconnectPeriod: 4000, // 重連時間間隔 // 認證信息 clientId: 'mqttjs_3be2c321', username: 'admin', password: '3Ha86294', }; this.client = mqtt.connect(this.url, options); this.client.on('error', (error: any) => { console.log(error); }); this.client.on('reconnect', (error: Error) => { console.log(error); }); } //取消訂閱 unsubscribes() { this.client.unsubscribe(this.topic, (error: Error) => { if (!error) { console.log(this.topic, '取消訂閱成功'); } else { console.log(this.topic, '取消訂閱失敗'); } }); } //連接 link() { this.client.on('connect', () => { this.client.subscribe(this.topic, (error: any) => { if (!error) { console.log('訂閱成功'); } else { console.log('訂閱失敗'); } }); }); } //收到的消息 get(callback: OnMessageCallback) { this.client.on('message', callback); // console.log(callback,"1010") } //結束鏈接 over() { this.client.end(); } } export default MQTT;
utils下面新建usemqtt.ts頁面
import MQTT from '@/utils/mqtt'; import { OnMessageCallback } from 'mqtt'; import { ref } from "vue"; export default function useMqtt() { const PublicMqtt = ref<MQTT | null>(null); const startMqtt = (val: string, callback: OnMessageCallback) => { //設置訂閱地址 PublicMqtt.value = new MQTT(val); //初始化mqtt PublicMqtt.value.init(); //鏈接mqtt PublicMqtt.value.link(); getMessage(callback); }; const getMessage = (callback: OnMessageCallback) => { // console.log(callback,"18") // PublicMqtt.value?.client.on('message', callback); // @ts-ignore //忽略提示 PublicMqtt.value?.get(callback); }; // onUnmounted(() => { // //頁面銷毀結束訂閱 // if (PublicMqtt.value) { // PublicMqtt.value.unsubscribes(); // PublicMqtt.value.over(); // } // }); return { startMqtt, }; }
使用頁面調用
import useMqtt from '@/utils/usemqtt'; const { startMqtt } = useMqtt(); startMqtt(deviceSnsss, (topic, message) => { console.log(message) }
或者
<template> <div id="app"> <div class="head"> <p>天潤商城后臺管理系統</p> </div> <div class="login"> <table border="0" cellspacing="20"> <tr> <td>用戶名:</td> <td> <el-input prefix-icon="iconfont icon-xingmingyonghumingnicheng" placeholder="請輸入賬號" v-model="account" clearable ></el-input> </td> </tr> <tr> <td>密碼:</td> <td> <el-input prefix-icon="iconfont icon-mima" placeholder="請輸入密碼" v-model="password" show-password ></el-input> </td> </tr> <tr> <td colspan="2" > <el-button type="danger" @click="login" >登錄</el-button > </td> </tr> </table> </div> </div> </template> <script> import mqtt from 'mqtt' export default { data() { return { account:"12", password:"12", connection: { host: 'www.liufengtec.com', port: 8084, endpoint: '/mqtt', clean: true, // 保留會話 connectTimeout: 4000, // 超時時間 reconnectPeriod: 4000, // 重連時間間隔 // 認證信息 clientId: 'mqttjs_3be2c321', username: 'admin', password: '3Ha86294', }, subscription: { topic: 'topic/mqttx', qos: 0, }, publish: { topic: 'topic/browser', qos: 0, payload: '{ "msg": "Hello, I am browser." }', }, receiveNews: '', qosList: [ { label: 0, value: 0 }, { label: 1, value: 1 }, { label: 2, value: 2 }, ], client: { connected: false, }, subscribeSuccess: false, } }, methods: { login(){ this.createConnection(); }, // 創建連接 createConnection() { let that=this; // 連接字符串, 通過協議指定使用的連接方式 // ws 未加密 WebSocket 連接 // wss 加密 WebSocket 連接 // mqtt 未加密 TCP 連接 // mqtts 加密 TCP 連接 // wxs 微信小程序連接 // alis 支付寶小程序連接 const { host, port, endpoint, ...options } = this.connection const connectUrl = `ws://www.liufengtec.com:8083/mqtt` try { this.client = mqtt.connect(connectUrl) } catch (error) { console.log('mqtt.connect error', error) } this.client.on('connect', () => { console.log('Connection succeeded!') that.subscribe(); }) this.client.on('error', error => { console.log('Connection failed', error) }) this.client.on('message', (topic, message) => { this.receiveNews = this.receiveNews.concat(message) console.log(`Received message ${message} from topic ${topic}`) }) }, //訂閱 subscribe() { var topic = "system"; var qos = 0; //logMessage("INFO", "Subscribing to: [Topic: ", topic, ", QoS: ", qos, "]"); this.client.subscribe(topic, { qos: Number(qos) }); }, // called when a message arrives message() { var topic = "system"; this.client.on("message", (topic, message) => { console.log(message) }); } } } </script> <style lang="less" scoped> .head { height: 150px; width: 100vw; background-image: url(../assets/banner.jpg); background-repeat: no-repeat; background-size: cover; p { font-size: 30px; color: white; line-height: 150px; margin-left: 50px; } } .bg-purple { background: #d3dce6; } .grid-content { border-radius: 4px; min-height: 36px; } .login { display: flex; flex-direction: column; justify-content: center; width: 400px; margin: 0px auto; border: 2px #f3f3f3 solid; padding: 100px; } </style>
不封裝直接使用。ws和wss不一樣
到此,相信大家對“vue3怎么使用mqtt”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。