Vue項目接入MQTT
安裝mqtt庫
mqtt 使用的版本是 3.0.0,高版本可能不對
"mqtt": "^3.0.0",
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>
發送mtqq
client.publish('/wjw/wjw', 'hhhhh', 0, error=> {
if(!error) {
console.log('----> ', '發送成功')
}
})
測試
mqtt模擬工具發送主題消息:
頁面收到的mqtt消息:
訂閱多個主題的,用逗號分隔,接收主題消息根據主題區分消息處理