安装
npm install mqtt
引入
import mqtt from 'mqtt'
Vue.prototype.mqtt = mqtt
页面中使用
import mqtt from 'mqtt'
methods:{
initMQTT() {
const connectUrl = 'ws://13.60.15.29:8083/mqtt';
let client = mqtt.connect(connectUrl, {
clean: true,
connectTimeout: 4000,
reconnectPeriod: 1000,
clientId: 'camellia-web' + Date.now(),
username: 'camellia-web'
})
const subscribe = ['/env_01/data/post', '/leak_01/data/post', '/smoke_01/data/post', '/dtu_01/data/post'];
client.on('connect', () => {
console.log('已经连接成功');
client.subscribe(subscribe, () => {
console.log(`订阅了主题 ${subscribe}`)
})
});
let _this = this;
client.on('message', function (topic, message) {
let data = JSON.parse(message.toString());
if (topic === subscribe[0]) {
_this.envData.temper = data.temper_1 + "℃";
_this.envData.humidity = data.humidity_1 + "%RH";
_this.envData.co = data.co_1 + "ppm";
_this.envData.co2 = data.co2_1 + "ppm";
_this.envData.pressure = data.pressure_1 + "pa";
_this.envData.pm25 = data['pm2.5_1'] + "ug/m³";
_this.envData.pm10 = data.pm10_1 + "ug/m³";
_this.envData.noise = data.noise_1 + "dB";
}
});
client.on("close", function () {
console.log("已断开连接")
});
},
}