VUE3结合mqtt解决多页面使用需重复连接等问题(封装)

场景

在做的一个项目中多个页面都需要使用到mqtt接收消息,但这样的话每个页面就都需要连接一次mqtt,并且要再次配置options信息、订阅主题、接收消息,非常的不方便,因此琢磨将mqtt封装到vuex中,使其可以多页面通用,这样只需要连接订阅一次,接收到的消息可以存储在vuex中。

一、安装mqtt

npm install mqtt

二、暴露出main.js中的vue实例

使用export default暴露出app

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

const app = createApp(App)

app.use(ElementPlus)
app.use(store).use(router).mount('#app')

export default app

三、封装mqtt

import { createStore } from 'vuex'
import main from "../main";//main.ts文件中要暴露app
import router from '@/router';// 引入vuex
export default createStore({
  state: {
    topics: [],//订阅话题
  },
  mutations: {
    //mqtt服务
    MQTT_SERVICE(state, event){
      // mqtt连接成功
      main.config.globalProperties.$mqtt.on('connect', (e) => {
        console.log('连接成功:', e)
        // console.log(state.topics)
        main.config.globalProperties.$mqtt.subscribe(state.topics, { qos: 1 }, (error) => {
          if (!error) {
            console.log('订阅成功')
          } else {
            console.log('订阅失败')
          }
        })
      })
      // 接收消息处理
      main.config.globalProperties.$mqtt.on('message', (topic, message) => {
        console.log('收到来自', topic, '的消息', message.toString())
      })
      // 断开发起重连
      main.config.globalProperties.$mqtt.on('reconnect', (error) => {
        console.log('正在重连:', error)
      })
      // 链接异常处理
      main.config.globalProperties.$mqtt.on('error', (error) => {
        console.log('连接失败:', error)
      })
    },
    //发布消息
    MQTT_PUBLISH(state, {topic, msg}){
      console.log(topic)
      main.config.globalProperties.$mqtt.publish(topic, msg)
    },
    //断开MQTT
    MQTT_CLOSE(state, event){
      console.log('断开MQTT');
      main.config.globalProperties.$mqtt.end()
    },
  },
  actions: {
  },
  modules: {
  }
})

四、编写mqtt配置文件

在src下的utils下新建一个js文件:mqttConfig.js

import $store from "@/store/index";
export function getOptions(){
  let options = {
    connectTimeout: 40000,
    clientId: 'mqttId',
    clean: true,
    username: admin,
    password: admin
  }
  return options
}

export function setTopics(){
  //此处修改VUEX中的值建议通过actions、mutations修改state值
  $store.state.topics = [ 'topic01','topic02','topic03''topic04''topic05']
}

五、页面引入并使用

这里是在一个所有页面都要用到的一个公共组件中引入使用的,也可以在main.js中使用(看引入方法二)

方法1. 公共组件中引用

import { computed, reactive, ref ,defineComponent, onMounted, onUnmounted } from 'vue-demi';
import $store from "@/store/index";//引入VUEX
import main from "../main";//main.ts文件中要暴露app
import { getOptions, setTopics } from "@/utils/mqttConfig.js"
import mqtt from 'mqtt'//引入mqtt
//mqtt链接地址
let mqttUrl = 'ws://broker.emqx.io:8084'
export default defineComponent ({
  name:'msgDisplay',
  setup(){
     onMounted(() => {
      //mqtt连接
      main.config.globalProperties.$mqtt = mqtt.connect(mqttUrl, getOptions())
      //设置订阅主题
      setTopics()
      //启动mqtt状态监听
      $store.commit('MQTT_SERVICE')
    })
    
    onUnmounted(() => {
      $store.commit('MQTT_CLOSE') //断开mqtt
    })
    
    return { }
  }    
})

方法2.

该方法需要在main中创建连接,在首页的渲染生命周期中启动mqtt状态监听

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

const app = createApp(App)

import mqtt from 'mqtt'
import { getOptions, setTopics } from "./utils/mqttConfig.js"
let mqttUrl = 'ws://broker.emqx.io:8084'
//mqtt连接
app.config.globalProperties.$mqtt = mqtt.connect(mqttUrl, getOptions())
//设置订阅主题
setTopics()

app.use(ElementPlus)
app.use(store).use(router).mount('#app')

export default app

首页.vue

你可能感兴趣的:(MQTT,前端,物联网)