export default { data() { return { clientId: "", mqttClientData: null,
mqttMessageBound: false, // 确保 message 事件只绑定一次 }; }, onLoad(options) {
const devItem = JSON.parse(options.devItem); this.clientId =
uni.getStorageSync("clientIDetail") || devItem.clientId; // 获取全局 MQTT 客户端
this.mqttClientData = this.$mqttClientData; // 如果还没创建或者未连接，等待连接
ready if (!this.mqttClientData || !this.mqttClientData.mqttDataConnected) {
uni.$once("mqttData-ready", (mqtt) => { this.mqttClientData = mqtt;
this.subscribeMqttData(); }); } else { this.subscribeMqttData(); } }, methods: {
subscribeMqttData() { const mqtt = this.mqttClientData; if (!mqtt) return; //
只绑定一次 message 回调 if (!this.mqttMessageBound) { mqtt.on("message", (topic,
message) => { console.log("收到消息:", topic, message.toString()); const
dataMatch = topic.match(/^\/dev\/(.+)\/tracker_targets$/); const cmdMatch =
topic.match(/^\/mps\/wx_(.+)\/notice$/); if (dataMatch && dataMatch[1] ===
this.clientId) { this.handleMessage(topic, message, this.clientId); } else if
(cmdMatch) { this.$refs.alarmModel?.hanOtherMessage?.(topic, message); } });
this.mqttMessageBound = true; } // 如果已连接，立即订阅 if
(mqtt.mqttDataConnected) { mqtt.subscribeTopic(this.clientId); } else { //
未连接时监听 connect 再订阅 mqtt.on("connect", () => { console.log("DATA MQTT
连接成功，订阅 topic"); mqtt.subscribeTopic(this.clientId); }); } }, },
onUnload() { // 页面卸载取消订阅 if (this.mqttClientData) {
this.mqttClientData.unsubscribe(`/dev/${this.clientId}/tracker_targets`, (err)
=> { if (err) console.error("取消订阅失败", err); else
console.log(`取消订阅成功: /dev/${this.clientId}/tracker_targets`); }); }
this.mqttMessageBound = false; }, };
