首页 > 其他分享 >Vue3连接mqtt订阅消息

Vue3连接mqtt订阅消息

时间:2024-04-02 16:36:34浏览次数:13  
标签:订阅 console Vue3 mqtt error var config port

Vue3 中使用以及订阅

没有安装可使用 npm install mqtt --save (暂时使用了npm install [email protected]

页面引入

引用mqtt库 不要直接引用mqtt 会报错
import mqtt from 'mqtt/dist/mqtt'

代码:

1.获取动态配置(关于mqtt的动态配置)

<script>
// //引入mqtt
import mqtt from "mqtt/dist/mqtt";
export default {
 data() {
    return {
      client: {},
    };
  },
  created() {
    this.getrtm_index_config(); //获取运行配置获取并建立mqtt
  },
  methods: {
    //运行配置获取并建立mqtt
    getrtm_index_config() {
      const rtm_index_config_url = "/api/kui/rtm_index_config?token=" + token;
      this.$myaxios.get(rtm_index_config_url).then((res) => {
        this.rtmindexconfig = res.data;
        this.mqttconnect(this.rtmindexconfig.mqtt);
      });
    },
  },
}
</script>

2.建立mqtt

    mqttconnect(_config) {
      var _port = _config.connection.port;
      var _path = "/ws";
      var _usessl = false;
      if (location.protocol == "https:") {
        _port = _config.connection.porthttps;
        _path = "/ws";
        _usessl = true;
      }
      var _hostname = _config.connection.hostname;
      if (_hostname == "") {
        //什么也都没有配置,那么按浏览器的来
        _hostname = location.hostname;
        var tport = location.port;
        if (tport == "") {
          if (_usessl) {
            tport = "443";
          } else {
            tport = "80";
          }
        }
        _port = parseInt(tport);
      }
      const options = {
        connectTimeout: 4000,
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间
        clientId: "emqx_vue_" + Math.random().toString(16).substring(2, 8), //唯一值
        port: _config.connection.port, //端口  port  9000
        host: _hostname, //地址
        username: _config.connection.username, //id
        password: _config.connection.password,
      };
      var controlWsUrl = `ws://${options.host}:${options.port}/ws`;
      console.error(controlWsUrl);
      //创建实例 传入地址和参数对象
      this.client = mqtt.connect(controlWsUrl, options);
      this.client.on("reconnect", (error) => {
        console.log("正在重连:", error);
      });
      //连接成功
      this.client.on("connect", (e) => {
        //订阅主题
        this.onConnect(_config);
        //监听接收信息
        this.getmqMessage();
      });
    },

mqtt地址例如:

3.订阅主题

    //订阅主题
    onConnect(_config) {
      console.error(_config.config.topic);
      var spichar = "/";
      var t = _config.config.topic + spichar + "all" + spichar + "#"; //匹配 iopmsglist/all iopmsglist/all/xxx
      this.client.subscribe(t, 0, (error, res) => {
        if (error) {
          console.log("订阅主题错误", error);
          return;
        }
        console.log("订阅主题", res);
      });
    },

4.监听接收信息

   //监听接收消息
    getmqMessage() {
      this.client.on("message", (topic, message) => {
        if (message) {
          console.error("收到来着", topic, "的信息", message.toString());
        }
      });
    },

 收到的信息需要toString,否则默认他是Uint8Array格式

 

标签:订阅,console,Vue3,mqtt,error,var,config,port
From: https://www.cnblogs.com/ZhuMeng-Chao/p/18110864

相关文章

  • Vue2 和 Vue3 中的 v-model 的区别#记录
    vue3对v-model的语法进行了改动。vue2中有两种方式实现数据的双向绑定(组件与外部数据的双向绑定),一种是使用v-model,另一种是使用v-bind.sync修饰符。vue2中的v-model,主要是进行value属性的绑定和input事件的派发。<ChildComponentv-model="pageTitle"/>//等价于<Child......
  • AppStore轻松订阅ChatGPT plus解锁GPT4的方法
    1、登录新账户1.1接着再次点击AppStore中右上角的头像,输入前面注册的美区账号&密码,点击 登录 即可。1.2点击付款方式,可以看到绑定成功的卡。这里我用的是556150的美元虚拟信用卡2、下载ChatGPTApp在AppStore里搜索ChatGPT或点击访问 ‎ChatGPTontheA......
  • vue3从精通到入门9:计算属性computed
    在Vue3中,computed 是一个用于创建计算属性的工具,它基于组件的响应式依赖进行复杂的计算,并返回一个新的响应式引用。计算属性是Vue的一个核心概念,它提供了一种声明式的方式来执行基于其依赖的响应式数据的计算。computed使用:计算属性与常规属性类似,但是它们是基于它们......
  • 【必看】Midjourney订阅前必看的十件事
    1.Midjourney是什么?Discord是什么?Midjourney是一款AI制图工具,只要关键字,就能透过AI算法生成相对应的图片,只需要不到一分钟。同时还可以选择不同画家的艺术风格,例如安迪华荷、达芬奇、达利和毕加索等,还能识别特定镜头或摄影术语。Discord是一家游戏聊天应用与社区的聊天软......
  • vue3 设置el-dialog height超过滚动条
     方法一:<stylescoped>::v-deep.el-dialog.el-dialog-body{height:500px;overflow-y:auto;}</style> 如果要设置动态的高度话,则要在setup里面设置 <script>exportdefaultdefineComponent({setup:{constcssContent=ref({heigh......
  • vue3中播放flv流视频,以及组件封装超全
    实现以上功能的播放,只需要传入一个流的地址即可,当然组件也只有简单的实时播放功能下面直接上组件里面的flvjs通过npmiflv.js直接下载 <template><divclass="player"style="position:relative;"><pstyle="position:absolute!important;top:10px;lef......
  • 大屏可视化项目示例--基于Vue3+vite2+echart+mock+axios+dataV
    图例: 项目环境:Vite、Echarts、Npm、Node、axios、mock、vue3、dataV。项目地址:IofTV-Screen-Vue3:......
  • Vue — Vue3.0状态管理工具Pinia
    一、什么是Pinia?Pinia是一个专门为Vue3设计的状态管理库。它的目标是提供一种简单、直观的方法来管理Vue应用的状态,同时充分利用Vue3的响应式系统和组合式API。Pinia主要特点包括:基于Vue3:Pinia是专门为Vue3设计的状态管理库,充分利用了Vue3的响应式系统......
  • RSS 一种简洁优雅的数据订阅方式
    拓展阅读RSS一种简洁优雅的数据订阅方式RSSHubEverythingisRSSible开源、易于使用且可扩展的RSS提要生成器RSS介绍RSS(ReallySimpleSyndication)是一种用于发布网站更新的标准格式。它允许用户获取网站内容的最新更新,而无需访问网站本身。RSS通常用于博客、新闻网站......
  • Vue3创建空对象方法及推荐
    当使用{}时,我们实际上是在告诉TypeScript将空对象断言为任意类型(any),从而绕过了类型检查。这种做法会失去类型安全性,但在某些特定情况下可能是一种解决方案。以下是示例代码和说明://使用<any>{}将空对象断言为any类型letobj=<any>{};//对空对象进行操作obj.f......