目前3.0的版本比较稳定
npm install mqtt@3.0.0
yarn add mqtt@3.0.0
<script>
import mqtt from 'mqtt'
export default {
data() {
return {
connection: {
host: '192.168.113.88',
port: 8083,
endpoint: '/mqtt',
clean: true,
connectTimeout: 4000,
reconnectPeriod: 4000,
clientId: 'mqttjs_3be2c321',
username: 'emqx_test',
password: 'emqx_test',
},
subscription: {
topic: 'topic/mqttx',
qos: 0,
},
publish: {
topic: 'topic/browser',
qos: 0,
payload: '{ "msg": "Hello, I am browser." }',
},
receiveNews: '',
qosList: [
{ label: 0, value: 0 },
{ label: 1, value: 1 },
{ label: 2, value: 2 },
],
client: {
connected: false,
},
subscribeSuccess: false,
}
},
methods: {
createConnection() {
const { host, port, endpoint, ...options } = this.connection
const connectUrl = `ws://${host}:${port}${endpoint}`
try {
this.client = mqtt.connect(connectUrl, options)
} catch (error) {
console.log('mqtt.connect error', error)
}
this.client.on('connect', () => {
console.log('Connection succeeded!')
})
this.client.on('error', error => {
console.log('Connection failed', error)ß
})
this.client.on('message', (topic, message) => {
this.receiveNews = this.receiveNews.concat(message)
console.log(`Received message ${message} from topic ${topic}`)
})
},
}
}
</script>
## 订阅主题
doSubscribe() {
const { topic, qos } = this.subscription
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)
})
},
## 取消订阅
doUnSubscribe() {
const { topic } = this.subscription
this.client.unsubscribe(topic, error => {
if (error) {
console.log('Unsubscribe error', error)
}
})
}
## 消息发布
doPublish() {
const { topic, qos, payload } = this.publication
this.client.publish(topic, payload, qos, error => {
if (error) {
console.log('Publish error', error)
}
})
}
断开连接
destroyConnection() {
if (this.client.connected) {
try {
this.client.end()
this.client = {
connected: false,
}
console.log('Successfully disconnected!')
} catch (error) {
console.log('Disconnect failed', error.toString())
}
}
}