在Vue中使用MQTTjs指北 | 您所在的位置:网站首页 › vue中引用js使用 › 在Vue中使用MQTTjs指北 |
最近需要用mqtt做项目,并且是在vue环境中,遇到各种问题,研究了两天,现在记录一下,做个简单的例子,避免再入坑。 0.脚手架中安装mqttMQTTjs官方地址:MQTT-Github 在脚手架中使用npm安装到项目: 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() })但是这个例子在vue中怎么用并不明显,现在写一下我的例子: 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 }); }这里需要注意this指向问题,刚开始的时候因为写的函数所以一直报错,后来把里面的函数换成箭头函数就好了。 4. 可以把发布消息函数写到methods里面 methods: { handleclick: function() { this.client.publish(this.mtopic, this.msg); } } 最后贴上完整代码 //vue单文件 收到的消息:{{msg}} 发布 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); } } }; |
CopyRight 2018-2019 实验室设备网 版权所有 |