一、先安装依赖插件
二、组件中的使用
// 先安装stompjs
npm install stompjs
utils文件中的mqtt.js内容:
mqtt.js
export const MQTT_SERVICE = 'ws://10.38.128.82:15674/ws' // mqtt服务地址
export const MQTT_USERNAME = 'tx' // mqtt连接用户名
export const MQTT_PASSWORD = 'tx' // mqtt连接密码
export const MQTT_host = 'tx' // mqtt交换机
export const MQTT_topic = '/exchange/PC_MESSAGE_LIINZHI/PC' // 订阅频道
组件中代码:test.vue
import Stomp from 'stompjs'
import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD,MQTT_host,MQTT_topic } from '@/utils/mqtt'
export default {
data() {
return {
title:'测试信息',
client: Stomp.client(MQTT_SERVICE),
listData: [
]
}
},
computed: {
optionSetting() {
return {
step: 1, // 速度,值越大,速度越快
hoverStop: true // 鼠标悬停效果,false为关闭该效果
// singleHeight: 120,//单行停顿
// waitTime: 2500,//单行停顿的时间
}
}
},
created() {
this.connect()// stomp连接mq
},
methods: {
onConnected: function(frame) {
// 订阅频道
const topic = MQTT_topic
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)
this.title=frame.body;
},
connect() {
// 初始化mqtt客户端,并连接mqtt服务
const headers = {
login: MQTT_USERNAME,
password: MQTT_PASSWORD
}
this.client.connect(MQTT_USERNAME,MQTT_PASSWORD, this.onConnected, this.onFailed,MQTT_host)
// this.client.connect(MQTT_USERNAME,MQTT_PASSWORD, this.onConnected, this.onFailed)// 有的是不需要MQTT_host的,不需要的话,就不用传这个参数
}
}
}