1.腳手架中安裝mqtt
npm install mqtt --save
官方有一個例子:
var mqtt = require('mqtt') var client = mqtt.connect('mqtt://test.mosquitto.org') client.on('connect', function () { client.subscribe('presence', function (err) { if (!err) { client.publish('presence', 'Hello mqtt') } }) }) client.on('message', function (topic, message) { // message is Buffer console.log(message.toString()) client.end() })
1.在vue文件中引入mqtt
import mqtt from 'mqtt'
2.在data中聲明client對象
data() { return { mtopic: "1101", msg: "", client: {} }; }
3. 在mounted鈎子中建立連接
mounted() { this.client = mqtt.connect("ws://ip:port", { username: "admin", password: "password" }); this.client.on("connect", e =>{ console.log("連接成功"); this.client.subscribe(this.mtopic, (err) => { if (!err) { console.log("訂閱成功:" + this.mtopic); } }); }); this.client.on("message", (topic, message) => { this.msg = message }); }
4. 可以把發布消息函數寫到methods里面
methods: { handleclick: function() { this.client.publish(this.mtopic, this.msg); } }
最后貼上完整代碼
<template> <div class="hello"> <h1>收到的消息:{{msg}}</h1> <button @click="handleclick">發布</button> </div> </template> <script> import mqtt from "mqtt"; export default { name: "HelloWorld", data() { return { mtopic: "1101", msg: "lalala", client: {} }; }, mounted() { this.client = mqtt.connect("ws://ip:port", { username: "admin", password: "password" }); this.client.on("connect", e =>{ console.log("連接成功"); this.client.subscribe(this.mtopic, (err)=> { if (!err) { console.log("訂閱成功:" + this.mtopic); } }); }); this.client.on("message", (topic, message) => { this.msg = message }); }, methods: { handleclick: function() { this.client.publish(this.mtopic, this.msg); } } }; </script>
轉自:https://blog.csdn.net/m0_37811924/article/details/102602914