Vue项目接入MQTT
安装mqtt库
npm install mqtt --save
Vue代码实现
<template>
<div id="app">
<p>mqtt收到的数据:</p>
<p>{{this.msg}}</p>
</div>
</template>
<script>
import mqtt from 'mqtt'
var client
const options = {
connectTimeout: 40000,
clientId: 'mqtitId-Home',
username: 'admin',
password: 'admin123',
clean: true
}
client = mqtt.connect('ws://172.80.5.222:8083/mqtt', options)
export default {
data() {
return {
msg: '--'
}
},
created() {
this.mqttMsg()
},
methods: {
mqttMsg() {
client.on('connect', (e) => {
console.log("连接成功!!!")
client.subscribe('/wjw1014', { qos: 0 }, (error) => {
if (!error) {
console.log('订阅成功')
} else {
console.log('订阅失败')
}
})
})
// 接收消息处理
client.on('message', (topic, message) => {
console.log('收到来自', topic, '的消息', message.toString())
this.msg = message.toString()
})
}
}
}
</script>
<style scoped>
</style>
测试
mqtt模拟工具发送主题消息:
页面收到的mqtt消息:
订阅多个主题的,用逗号分隔,接收主题消息根据主题区分消息处理
来源:oschina
链接:https://my.oschina.net/u/4415401/blog/3324961