vue结合mqtt

时间:2020-05-23
本文章向大家介绍vue结合mqtt,主要包括vue结合mqtt使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、初始化一个vue项目

vue init webpack vuemqtt

npm install

npm run dev

二、安装mqtt

npm install mqtt --save

三、编写vue组件

 1 <template>
 2   <div id="app">
 3     <p>mqtt收到的数据:</p>
 4     <p>{{this.msg}}</p>
 5   </div>
 6 </template>
 7 
 8 <script>
 9 
10   import mqtt from 'mqtt'
11 
12   var client
13   const options = {
14     connectTimeout: 40000,
15     clientId: '',
16     username: 'admin',
17     password: 'admin',
18     clean: true
19   }
20   client = mqtt.connect('ws://120.79.x.x:8083',options)   //此处不应该为1883,应该在mosquitto消息服务器中配置8003端口为websocket
21   export default {
22     data() {
23       return {
24         msg: '--'
25       }
26     },
27 
28     created() {
29       this.mqttMsg()
30     },
31 
32     methods: {
33       mqttMsg() {
34         client.on('connect', (e) => {
35           console.log("连接成功!!!")
36           client.subscribe('data/receive', { qos: 0 }, (error) => {
37             if (!error) {
38               console.log('订阅成功')
39             } else {
40               console.log('订阅失败')
41             }
42           })
43 
44         })
45         // 接收消息处理
46         client.on('message', (topic, message) => {
47           console.log('收到来自', topic, '的消息', message.toString())
48           this.msg = message.toString()
49         })
50       }
51     }
52 
53 
54   }
55 </script>
56 <style scoped>
57 </style>
mqtt.vue

注意:在mosquitto消息服务器中配置websocket并监听8083  查看详情

原文地址:https://www.cnblogs.com/nuister/p/12944041.html