当前位置:首页 > VUE

vue界面实现mqtt

2026-03-28 20:42:24VUE

Vue 实现 MQTT 通信

安装 MQTT 客户端库

在 Vue 项目中安装 mqtt 库:

npm install mqtt --save

创建 MQTT 连接

在 Vue 组件中引入 mqtt 并建立连接:

import mqtt from 'mqtt'

export default {
  data() {
    return {
      client: null,
      message: ''
    }
  },
  mounted() {
    this.connectMqtt()
  },
  methods: {
    connectMqtt() {
      const options = {
        clean: true,
        connectTimeout: 4000,
        clientId: 'vue-client-' + Math.random().toString(16).substr(2, 8)
      }

      this.client = mqtt.connect('ws://mqtt.eclipseprojects.io:80/mqtt', options)

      this.client.on('connect', () => {
        console.log('Connected to MQTT broker')
        this.client.subscribe('vue/demo')
      })

      this.client.on('message', (topic, payload) => {
        this.message = payload.toString()
      })

      this.client.on('error', (error) => {
        console.error('MQTT error:', error)
      })
    }
  },
  beforeDestroy() {
    if (this.client) {
      this.client.end()
    }
  }
}

发布消息

添加发布消息的方法:

methods: {
  publishMessage() {
    if (this.client && this.client.connected) {
      this.client.publish('vue/demo', 'Hello from Vue')
    }
  }
}

模板部分

在模板中添加交互元素:

vue界面实现mqtt

<template>
  <div>
    <button @click="publishMessage">发送消息</button>
    <p>接收到的消息: {{ message }}</p>
  </div>
</template>

安全配置

生产环境应考虑安全配置:

const options = {
  username: 'your-username',
  password: 'your-password',
  reconnectPeriod: 1000
}

断线重连

添加断线重连逻辑:

vue界面实现mqtt

this.client.on('close', () => {
  console.log('Connection closed, attempting to reconnect...')
  setTimeout(this.connectMqtt, 5000)
})

主题管理

实现动态主题订阅:

subscribeToTopic(topic) {
  if (this.client && this.client.connected) {
    this.client.subscribe(topic, { qos: 1 })
  }
}

unsubscribeFromTopic(topic) {
  if (this.client && this.client.connected) {
    this.client.unsubscribe(topic)
  }
}

QoS 设置

设置消息质量等级:

this.client.publish('vue/demo', 'Important message', { qos: 2 })

保留消息

发送保留消息:

this.client.publish('vue/demo', 'Retained message', { retain: true })

标签: 界面vue
分享给朋友:

相关文章

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed: {…

vue实现autocomplete

vue实现autocomplete

Vue 实现 Autocomplete 功能 Vue 中实现 Autocomplete(自动完成)功能可以通过自定义组件或使用现有库完成。以下是几种常见方法: 方法一:使用 Vue 原生实现 创建…

vue 指令实现

vue 指令实现

Vue 指令实现 Vue 指令是 Vue.js 提供的特殊属性,用于在 DOM 元素上添加特殊行为。指令以 v- 前缀开头,例如 v-model、v-if、v-for 等。以下是实现自定义指令和常用内…

vue实现input

vue实现input

Vue 实现 Input 输入框的方法 基本双向绑定 使用 v-model 指令实现双向数据绑定,适用于大多数表单场景: <template> <input v-model="…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

vue实现选择

vue实现选择

Vue 实现选择功能的方法 在 Vue 中实现选择功能可以通过多种方式完成,以下介绍几种常见的实现方法。 使用 v-model 绑定单选 通过 v-model 可以轻松实现单选功能。以下是一个简单的…