YangYuGang
2025-03-05 6cc2d85787171281c269f4a6c3290b4a0762bcb6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<template>
  <div style="margin: auto 10px;">
    <!-- <p></p>
    <p>订阅的主题</p>
    <input type="text">
    <p>发布信息</p>
    <input type="text">
    <button style="color:aquamarine;background-color: brown;" @click="">发送</button>
    &nbsp;
    <div style="background-color:darkgrey;height: 500px; width: 500px;position:relative;left: 260px;top:-110px">
 
    </div> -->
  </div>
 
</template>
<script lang="ts">
import { defineComponent, ref, unref } from 'vue';
import  mqtt  from 'mqtt';
var client
const options={
  port:8083,
  connectTimeout:4000,
  clientId:'mqtt_'+ Math.random().toString(16),
}
client = mqtt.connect('ws://broker.emqx.io/mqtt',options)
export default {
  name: 'Helloworld',
  data(){
    return{
      msg:'Welcome to Your Vue.js App'
    }
  },
  created(){
    this.mqttMsg()
  },
  methods:{
    mqttMsg(){
      client.on('connect',(e)=>{
        console.log('连接成功')
        client.subscribe('sensor/1/temperature',{qos:0},(error)=>{
          console.log(error)
        })
        client.on("message",(topic,message)=>{
          console.log('收到来自',topic,'的消息',message.toString())
          if(message.toString()=='hi'){
            client.publish('testtopic/one','hello',{
              qos:0,rein:false
            },(error)=>{
              console.log('error',error)
            })
          }
        })
        // client.on("reconnect",(error)=>{
        //   console.log('正在重连',error)
        // })
        // client.on("reconnect",(error)=>{
        //   console.log('连接失败',error)
        // })
      })
    }
  }
  
}
</script>