千家信息网

Vue项目中MQTT如何使用

发表于:2024-09-27 作者:千家信息网编辑
千家信息网最后更新 2024年09月27日,本篇文章为大家展示了 Vue项目中MQTT如何使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。安装 MQTT 客户端库通过命令行安装:可以使用 npm 或
千家信息网最后更新 2024年09月27日Vue项目中MQTT如何使用

本篇文章为大家展示了 Vue项目中MQTT如何使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

安装 MQTT 客户端库

  1. 通过命令行安装:

    可以使用 npm 或 yarn 命令,二者选一

  • npm install mqtt --save


  • yarn add mqtt


  1. 通过 CDN 引入


  2. 下载到本地,然后使用相对路径引入


MQTT 的使用

连接 MQTT 服务器

本文将使用 EMQ X 提供的 免费公共 MQTT 服务器,该服务基于 EMQ X 的 MQTT 物联网云平台 创建。服务器接入信息如下:

  • Broker: broker.emqx.io

  • TCP Port: 1883

  • Websocket Port: 8083

连接关键代码:

订阅主题

doSubscribe() {  const { topic, qos } = this.subscription  this.client.subscribe(topic, qos, (error, res) => {    if (error) {      console.log('Subscribe to topics error', error)      return    }    this.subscribeSuccess = true    console.log('Subscribe to topics res', res)   })},

取消订阅

doUnSubscribe() {  const { topic } = this.subscription  this.client.unsubscribe(topic, error => {    if (error) {      console.log('Unsubscribe error', error)    }  })}

消息发布

doPublish() {  const { topic, qos, payload } = this.publication  this.client.publish(topic, payload, qos, error => {    if (error) {      console.log('Publish error', error)    }  })}

断开连接

destroyConnection() {  if (this.client.connected) {    try {      this.client.end()      this.client = {        connected: false,      }      console.log('Successfully disconnected!')    } catch (error) {      console.log('Disconnect failed', error.toString())    }  }}

上述内容就是 Vue项目中MQTT如何使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。

0