Vue項目接入MQTT


Vue項目接入MQTT

安裝mqtt庫

mqtt 使用的版本是 3.0.0,高版本可能不對

"mqtt": "^3.0.0",
npm install mqtt --save

Vue代碼實現

<template>
  <div id="app">
    <p>mqtt收到的數據:</p>
    <p>{{this.msg}}</p>
  </div>
</template>

<script>

  import mqtt from 'mqtt'

  var client
  const options = {
    connectTimeout: 40000,
    clientId: 'mqtitId-Home',
    username: 'admin',
    password: 'admin123',
    clean: true
  }
  client = mqtt.connect('ws://172.80.5.222:8083/mqtt', options)
  export default {
    data() {
      return {
        msg: '--'
      }
    },

    created() {
      this.mqttMsg()
    },

    methods: {
      mqttMsg() {
        client.on('connect', (e) => {
          console.log("連接成功!!!")
          client.subscribe('/wjw1014', { qos: 0 }, (error) => {
            if (!error) {
              console.log('訂閱成功')
            } else {
              console.log('訂閱失敗')
            }
          })

        })
        // 接收消息處理
        client.on('message', (topic, message) => {
          console.log('收到來自', topic, '的消息', message.toString())
          this.msg = message.toString()
        })
      }
    }


  }
</script>
<style scoped>
</style>

發送mtqq

client.publish('/wjw/wjw', 'hhhhh', 0, error=> {
   if(!error) {
       console.log('----> ', '發送成功')
   }
})

測試

mqtt模擬工具發送主題消息:

頁面收到的mqtt消息:

訂閱多個主題的,用逗號分隔,接收主題消息根據主題區分消息處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM