在vue中使用mqtt.js

mqtt.js 官网地址: MQTT
若是采用JS使用MQTT,详见

1. 脚手架中安装mqtt

npm install mqtt --save

官网例子:

const mqtt = require('mqtt')
const client  = mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', function () {
	client.subscribe('presence', function (err) {
		if (!err) {
			client.publish('presence', 'Hello mqtt')
		}
	})
})

client.on('message', function (topic, message) {
	// message is Buffer
	console.log(message.toString())
	client.end()
})

2. 在vue文件中引入mqtt

import mqtt from 'mqtt'

3. 在data中声明client对象

data() {
	return {
		client: {},
		mtopic: '订阅的主题',
		msg: '返回的消息'
	};
},

4. 在mounted钩子中建立连接

mounted() {
	this.client = mqtt.connect("ws://ip:port", {
		username: "admin",
		password: "password",
		keepalive: 15 //心跳保持时间(秒)
	});
	
	this.client.on("packetreceive", (e) => {
		if (e.cmd == "pingresp") {
			//console.log("发送心跳", e);
		}
	});
	
	// 连接成功后 - 订阅主题
	this.client.on("connect", e =>{
		console.log("连接成功");
		this.client.subscribe(this.mtopic, (err) => {
			if (!err) {
				console.log("订阅成功:" + this.mtopic);
			}
		});
	});
	
	// 连接成功后 - 返回的订阅内容
	this.client.on("message", (topic, message) => {
		this.msg = message;
	});
}

5. 发布消息

<el-button @click="publishTopic()">el-button>
publishTopic() {
	this.client.publish('订阅的主题名称', JSON.stringify(
		{
			// 条件
			"deptAreaId": this.currentUser.deptAreaId,
			"code": 1,
		}
	));
},

6. 实际案例

data() {
	return {
		client: {},
		parkTopic: "",
		parkPrefix: "parking/",
	};
},
mounted() {
	// 订阅的主题
	this.parkTopic = this.parkPrefix + this.currentUser.parkingId;
	// 连接MQTT
	this.connectMqtt();
},
methods: {
	connectMqtt() {
		// "ws://192.168.0.101:15675/ws"
		let wsUrl = process.env.VUE_APP_WS_URL || "ws://" + location.hostname + ":15675/ws";
	
		// MQTT 连接
		this.client = mqtt.connect(wsUrl, {
			username: process.env.VUE_APP_WS_USER || "admin",
			password: process.env.VUE_APP_WS_PWD || "123456",
			keepalive: 15//心跳保持时间(秒)
		});
		
		this.client.on("packetreceive", (e) => {
			if (e.cmd == "pingresp") {
				//console.log("发送心跳", e);
			}
		});
	
		// 连接成功后 - 订阅主题
		this.client.on("connect", e => {
			console.log("连接成功", Date.now());
			this.onSubscribe();
		});
	
		// 连接成功后 - 返回的订阅内容
		this.client.on("message", (topic, message) => {
			this.onMessage(topic, message);
		});
	},
	// 订阅主题
	onSubscribe() {
		
		this.client.subscribe(this.parkTopic, (err) => {
			if (!err) {
				console.log("订阅派车单成功:" + this.parkTopic);
			}
		});
	},
	// 接收消息
	onMessage(topic, message) {
		if (topic.indexOf(this.parkTopic) > -1) {
			var msg = JSON.parse(message);
			...
		}
	},
},
		

你可能感兴趣的:(Element-UI,Vue.js,element-ui,vue.js,MQTT)