您的位置:首页 > Web前端 > Vue.js

在Vue中使用MQTTjs指北

2020-02-03 02:06 1086 查看

最近需要用mqtt做项目,并且是在vue环境中,遇到各种问题,研究了两天,现在记录一下,做个简单的例子,避免再入坑。

0.脚手架中安装mqtt

MQTTjs官方地址: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单文件
<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>
  • 点赞
  • 收藏
  • 分享
  • 文章举报
菜鸡联盟德莱文 发布了3 篇原创文章 · 获赞 0 · 访问量 20 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: