vue连接mqtt:
-
首先导入五个依赖:
-
mqtt依赖:
npm install mqtt
-
webpack 依赖:
npm install webpack
-
buffer 依赖:
npm install buffer
-
process 依赖:
npm install process
-
url 依赖:
npm install url
-
-
第二步:在 vue.config.js 文件中进行配置
//首先导入 webpack const webpack =require("webpack") //进行配置 configureWebpack: { plugins: [ new webpack.ProvidePlugin({ process: 'process/browser', Buffer: ['buffer', 'Buffer'] }) ] }
-
第三步:以下即是一个组件例子 可直接插入引用
-
更改位置:
host: "broker.emqx.io",//链接地址 port:"8083",//端口 subscription: { topic: "suiji",//订阅主题 qos: 0, //qos配置 },
-
例程
<template> <div> <h2>你好</h2> <h3>{{msg}}</h3> <button @click="show">点我发数据</button> </div> </template> <script> import mqtt from "mqtt"; export default { name: "MqttTable", data() { return { connection: { host: "broker.emqx.io",//链接地址 port:"8083",//端口 endpoint: "/mqtt", clean: true, // 保留会话 connectTimeout: 4000, // 超时时间 reconnectPeriod: 4000, // 重连时间间隔 // 认证信息 clientId: "mqttjs_3be2c321" + new Date().getTime(), username: "",//用户名 不用的话什么也不用填 password: "",//密码 不用的话什么也不用填 }, subscription: { topic: "suiji", qos: 0, }, receiveNews: "", client: { connected: false, }, subscribeSuccess: false, msg:null, }; }, created() { }, mounted() { this.createConnection(); }, methods: { createConnection() { // 连接字符串, 通过协议指定使用的连接方式 // ws 未加密 WebSocket 连接 // wss 加密 WebSocket 连接 // mqtt 未加密 TCP 连接 // mqtts 加密 TCP 连接 // wxs 微信小程序连接 // alis 支付宝小程序连接 const {host, port, endpoint, ...options} = this.connection; const connectUrl = `ws://${host}:${port}${endpoint}`; const {topic, qos} = this.subscription; try { this.client = mqtt.connect(connectUrl, options); } catch (error) { console.log("mqtt.connect error", error); } //连接mqtt this.client.on("connect", () => { console.log("Connection succeeded!"); //订阅 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); }); }); this.client.on("error", (error) => { console.log("Connection failed", error); }); //获取消息 this.client.on("message", (topic, message) => { console.log(message.toString()) this.msg=message.toString() }); //下发 两个参数,一个是定义的topic另一个是你需要下发的内容 this.client.publish('topic', content) }, //这里只是将上面的发布代码单独提到一个函数中进行调用 show() { //下发 两个参数,一个是定义的topic另一个是你需要下发的内容 this.client.publish('this.subscription.topic', "你好吗") console.log("我要发消息了") }, }, destroyed() { }, } </script> <style scoped> </style>
-