1、安装依赖
yarn add mqtt
2、引入
import mqtt from ‘mqtt‘
3、完整项目代码
export default { data() { return { connection: { host: ‘xx.xx.xx.xx‘, port: 8080, connectTimeout: 4000, // 超时时间 reconnectPeriod: 4000, // 重连时间间隔 username: ‘admin‘, password: ‘123456‘, }, client: { connected: false, }, // 订阅的频道和事件 topicList: { "/ship/gps/100": "mqttShipShow" } } }, created() { this.createConnection() }, methods: { // 创建连接 createConnection() { const { host, port, endpoint, ...options } = this.connection const connectUrl = `mqtt://${host}:${port}/mqtt` try { this.client = mqtt.connect(connectUrl, options) } catch (error) { console.log(‘mqtt.connect error‘, error) } this.client.on(‘connect‘, () => { console.log(‘Connection succeeded!‘) // 不会订阅多个频道,所以遍历对象,循环监听多个频道 for (let key in this.topicList) { this.client.subscribe(key, (err) => { if (!err) { console.log(`订阅‘${key}‘成功`); } }); } }) this.client.on(‘error‘, error => { console.log(‘Connection failed‘, error) }) /** * topic: 监听的频道 * message: 返回的数据 */ this.client.on(‘message‘, (topic, message) => { this[this.topicList[topic]](message) }) }, mqttShipShow(message) { const row = JSON.parse(message) // 处理逻辑 fn(row) } }, }