zoukankan      html  css  js  c++  java
  • Vue项目接入MQTT

    Vue项目接入MQTT

    安装mqtt库

    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>
    

    测试

    mqtt模拟工具发送主题消息:

    页面收到的mqtt消息:

    订阅多个主题的,用逗号分隔,接收主题消息根据主题区分消息处理

  • 相关阅读:
    规矩与管理
    信息系统叫设施比叫工具更贴近本义
    让ansbile和docker愉快的在一起
    elasearch基础教程
    markdown语法
    python 实用pickle序列化
    python 解析配置文件
    ansible状态管理
    haproxy官方配置文档地址
    ansible操作模块相关
  • 原文地址:https://www.cnblogs.com/wjw1014/p/12090324.html
Copyright © 2011-2022 走看看