标签:服务 class none min clean temp rom 一个 webp
一、初始化一个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>
注意:在mosquitto消息服务器中配置websocket并监听8083 查看详情
标签:服务 class none min clean temp rom 一个 webp
原文地址:https://www.cnblogs.com/nuister/p/12944041.html