一、先安装依赖插件
// 先安装stompjs
npm install stompjs
二、组件中的使用
新建mqtt.js文件存储服务器信息:
export const MQTT_SERVICE = 'ws://25.30.9.137:15674/ws' // mqtt服务地址
export const MQTT_USERNAME = 'guest' // mqtt连接用户名
export const MQTT_PASSWORD = 'guest' // mqtt连接密码
import Stomp from "stompjs";
import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD } from "../config/mqtt";//引用mqtt.js
export default {
data() {
return {
client: Stomp.client(MQTT_SERVICE)
};
},
created() {
this.connect();
},
methods: {
onConnected: function(frame) {
//订阅频道
const topic = "/exchange/BaseDataExchange/routeData.alarm.65";
this.client.subscribe(topic, this.responseCallback, this.onFailed);
},
onFailed: function(frame) {
console.log("MQ Failed: " + frame);
},
responseCallback: function(frame) {
console.log("MQ msg=>" + frame.body);
//接收消息处理
},
connect: function() {
//初始化mqtt客户端,并连接mqtt服务
const headers = {
login: MQTT_USERNAME,
passcode: MQTT_PASSWORD
};
this.client.connect(headers, this.onConnected, this.onFailed);
}
}
};