Files
smart_storage_app/uni_modules/yh-wsmqtt/wsmqtt/components/mqtt-client.vue
pengqiao1993 e1798023c2 mqtt
2026-03-10 16:36:41 +08:00

96 lines
1.9 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<view>
<!-- MQTT 客户端组件 -->
<slot :connect="connect" :disconnect="disconnect" :publish="publish" :subscribe="subscribe" :unsubscribe="unsubscribe" :status="status" :topics="topics">
<!-- 默认插槽内容用户可自定义 -->
</slot>
</view>
</template>
<script>
import MQTTClient from '../js_sdk/index.js'
export default {
name: 'mqtt-client',
props: {
options: {
type: Object,
default: () => ({})
}
},
data() {
return {
mqtt: null,
status: 'disconnected',
topics: []
}
},
created() {
this.mqtt = new MQTTClient(this.options)
this.mqtt.on('statusChange', (status) => {
this.status = status
this.$emit('status-change', status)
})
this.mqtt.on('message', (msg) => {
this.$emit('message', msg)
})
this.mqtt.on('connect', () => {
this.$emit('connect')
})
this.mqtt.on('disconnect', (res) => {
this.$emit('disconnect', res)
})
this.mqtt.on('error', (error) => {
this.$emit('error', error)
})
},
beforeDestroy() {
if (this.mqtt) {
this.mqtt.disconnect()
}
},
methods: {
connect() {
if (this.mqtt) {
this.mqtt.connect()
}
},
disconnect() {
if (this.mqtt) {
this.mqtt.disconnect()
}
},
publish(topic, message, qos = 0) {
if (this.mqtt) {
this.mqtt.publish(topic, message, qos)
}
},
subscribe(topic, qos = 0) {
if (this.mqtt) {
this.mqtt.subscribe(topic, qos)
if (!this.topics.includes(topic)) {
this.topics.push(topic)
}
}
},
unsubscribe(topic) {
if (this.mqtt) {
this.mqtt.unsubscribe(topic)
const index = this.topics.indexOf(topic)
if (index > -1) {
this.topics.splice(index, 1)
}
}
}
}
}
</script>
<style>
</style>