在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>
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 使用vue-router设置每个页面的title方法
- vue脚手架及vue-router基本使用
- Vue的使用--简单学生信息录入系统
- vuejs使用FormData对象,ajax上传图片文件
- bing Map 在vue项目中的使用详解
- 使用CDN方法的方式进行Vue.js的安装
- VUE学习笔记-路由使用
- 开发vue但不使用vue-cli和webpack相关注意事项
- Vue使用vue-resouce和axios分别获取端口数据的
- 关于vue组件中定时器中只能使用箭头函数的问题
- vue中使用jsx语法
- 浅谈 Axios 在 Vue 项目中的使用
- angular、vue使用感受
- Vue使用NPM方式搭建项目
- vue的使用和知识点总结
- VS Code使用之Vue工程配置eslint
- 百度富文本在vue项目中的使用
- nuxt中vuex的使用
- vue订餐app,使用vue-router
- vue-cli(vue2.x)中使用vux(vue移动端UI组件库)