场景:在做的一个项目中多个页面都需要使用到mqtt接收消息,但这样的话每个页面就都需要连接一次mqtt,并且要再次配置options信息、订阅主题、接收消息,非常的不方便,因此琢磨将mqtt封装到vuex中,使其可以多页面通用,这样只需要连接订阅一次,接收到的消息可以存储在vuex中。
mqtt在线测试工具:http://www.emqx.io/online-mqtt-client
npm install mqtt
使用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服务封装到VUEX中,可以解决多页面需要用到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: {
}
})
在src下的utils下新建一个js文件:mqttConfig.js
更多options配置参数参考mqtt文档:https://github.com/mqttjs/MQTT.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中使用(看引入方法二)
方法一:公共组件中引入
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 { }
}
})
</script>
方法二:main中引入
该方法需要在main中创建连接,在首页的渲染生命周期中启动mqtt状态监听
main.js:
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:
<script>
import { onMounted, defineComponent, onUnmounted } from 'vue';
import $store from "@/store/index";
export default defineComponent ({
setup(){
onMounted(() => {
//启动mqtt状态监听
$store.commit('MQTT_SERVICE')
})
onUnmounted(() => {
//关闭项目时断开mqtt
//此处仅适用于从首页跳转到下一个页面后首页没有被销毁的情况,其它情况自行修改
$store.commit('MQTT_CLOSE')
})
}
})
</script>
至此mqtt封装结束,此文为mqtt使用过程中的个人封装笔记,如有不足或可改进之处还请指出。
转载请附带出处,谢谢!