1.引入mqtt.js
npm install mqtt@3.0.0
2.在/utils/mqtt.js中配置连接
export const MQTT_IP = '192.168.9.128:8083/mqtt'//mqtt地址端口
const MQTT_USERNAME = 'public'//mqtt用户名
const MQTT_PASSWORD = 'public'//密码
export const MQTT_OPTIONS = {
connectTimeout: 5000,
clientId: '',//不能重复
username: MQTT_USERNAME,
password: MQTT_PASSWORD,
clean: false
}
3.引入mqtt.js
import {
MQTT_IP,
MQTT_OPTIONS
} from '@/util/mqtt.js'
var mqtt = require('mqtt/dist/mqtt.js')
var client
export default {
data() {
return {
topic: "10001_weight",
client:{},
state:1
}
},
4.连接mqtt,将连接与data中初始化的变量client绑定,方便后面其他函数方法的使用
//订阅接口
Connect_Mqtt() {
this.client = mqtt.connect('wxs://' + MQTT_IP + "/mqtt", MQTT_OPTIONS)
this.client.on('connect', () => {
console.log('连接成功!')
//订阅
this.client.subscribe(this.topic, (err) => {
if (!err) {
console.log('订阅成功!' + err)
}
}).on('reconnect', (err) => {
console.log('正在重连...' + this.topic)
}).on('end', (err) => {
console.log('连接断开!')
}).on('close', function() {
console.log('断开连接')
}).on('offline', function() {
console.log('客户端下线')
}).on('message', (topic, message) => {
//收到数据后
try {
const data = JSON.stringify(message)
console.log('接收推送信息:', data)
} catch (e) {
console.log("失败Caught: " + e.message)
//失败关闭订阅
this.client.unsubscribe(this.topic, () => {
console.log("已关闭");
})
}
})
})
},
5.发布,取消订阅,断开连接(需要重新初始化,否则有可能重连导致相同id冲突)
dissubscribe() {
const that = this
that.client.unsubscribe(this.topic, () => {
console.log("已取消订阅");
})
},
disconnect(){
const that = this
that.client.end();
console.log("关闭");
this.client={}
},
publish(){
const that = this
that.client.publish('主题', '这是一条神秘的信息',(error)=>{
if (error) {
console.log(error)
} else {
console.log('Published')
}
})
}