Vue 是一款由尤雨溪及其团队开发的渐进式 Javascript 前端框架。该框架具备数据双向绑定、组件化、响应式和轻量等特点,搭配其脚手架 Vue CLI 使得开发者更加容易上手,大大减少了学习成本。同时其配备一个专用的状态管理模式 Vuex ,在这里可以集中管理所有组件的状态。
MQTT 是一种基于发布/订阅模式的 轻量级物联网消息传输协议。该协议提供了一对多的消息分发和应用程序的解耦,具备很小的传输消耗和协议数据交换、最大限度减少网络流量和三种不同消息服务质量等级,满足不同投递需求的优势。
本文主要介绍如何在 Vue 项目中使用 MQTT,实现客户端与 MQTT 服务器的连接、订阅、收发消息、取消订阅等功能。
参考链接如下:
示例:
vue create vue-mqtt-test
通过命令行安装:
可以使用 npm 或 yarn 命令,二者选一
npm install mqtt --save
yarn add mqtt
通过 CDN 引入
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js">script>
下载到本地,然后使用相对路径引入
<script src="/your/path/to/mqtt.min.js">script>
本文将使用 EMQ X 提供的 免费公共 MQTT 服务器,该服务基于 EMQ X 的 MQTT 物联网云平台 创建。服务器接入信息如下:
连接关键代码:
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 编写了如下简单的浏览器应用,该应用具备:创建连接、订阅主题、收发消息、取消订阅、断开连接等功能。
项目完整代码请见:https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Vue.js。
使用 MQTT 5.0 客户端工具 - MQTT X 作为另一个客户端进行消息收发测试。
在 MQTT X 发送第二条消息之前,在浏览器端进行取消订阅操作,浏览器端将不会收到 MQTT X 发送的后续消息。
综上所述,我们实现了在 Vue 项目中创建 MQTT 连接,模拟了客户端与 MQTT 服务器进行订阅、收发消息、取消订阅以及断开连接的场景。
Vue 作为三大主流的前端框架之一,既能够在浏览器端使用,也能够在移动端使用,结合 MQTT 协议及 MQTT 物联网云服务 可以开发出很多有趣的应用,比如客服聊天系统或实时监控物联网设备信息的管理系统。
版权声明: 本文为 EMQ 原创,转载请注明出处。
原文链接:https://www.emqx.io/cn/blog/how-to-use-mqtt-in-vue