1.首先,使用npm安装MQTT.js库
npm install mqtt
2.代码示例
<script>
import mqtt from 'mqtt'
export default {
created() {
// 创建一个连接到MQTT broker的客户端实例
const client = mqtt.connect('mqtt://broker.example.com')
// 连接成功后,订阅一个主题
client.on('connect', function () {
client.subscribe('myTopic', function (err) {
if (!err) {
console.log('成功订阅 myTopic 主题!')
}
})
})
// 监听订阅主题上的消息
client.on('message', function (topic, message) {
// 处理接收到的消息
console.log('收到主题 ' + topic + ' 的消息: ' + message.toString())
})
}
}
</script>