引入:.vue文件里面 import mqtt from 'mqtt/dist/mqtt'
<template>
<div class="login-box">
</div>
</template>
<script>
import mqtt from 'mqtt/dist/mqtt'
export default {
name: "login",
mounted() {
this.connect();
},
data() {
return {
ruleForm: {
password: "",
userName: "",
},
client: {},
msg:""
};
},
methods: {
//连接服务器
connect() {
let options = {
username: "",
password: "",
cleanSession : false,
keepAlive:60,
clientId: "mqttjs_" + Math.random().toString(16).substr(2, 8),
connectTimeout: 4000
}
this.client = mqtt.connect("ws://192.168.7.214:8083/mqtt",options);
this.client.on("connect", (e)=>{
console.log("成功连接服务器:",e);
//订阅三个名叫"top/#", "three/#"和"#"的主题
this.client.subscribe("/login", { qos: 1 }, (err)=> {
if (!err) {
console.log("订阅成功");
//向主题叫“pubtop”发布一则内容为"hello,this is a nice day!"的消息
this.publish("pubtop", "hello,this is a nice day!")
} else {
console.log("消息订阅失败!")
}
});
});
//重新连接
this.reconnect()
//是否已经断开连接
this.mqttError()
//监听获取信息
this.getMessage()
},
//监听接收消息
getMessage() {
this.client.on("message", (topic, message) => {
if(message) {
console.log("收到来着", topic, "的信息", message.toString());
const res = JSON.parse(message.toString());
console.log(res, "res");
this.msg = message;
this.ruleForm.userName = 'yong';
this.ruleForm.password = '123456';
}
});
},
//监听服务器是否连接失败
mqttError() {
this.client.on("error",(error) => {
console.log("连接失败:",error)
this.client.end()
})
},
//监听服务器重新连接
reconnect() {
this.client.on("reconnect", (error) => {
console.log("正在重连:", error)
});
},
//发布消息@topic主题 @message发布内容
publish(topic,message) {
if (!this.client.connected) {
console.log("客户端未连接")
return
}
this.client.publish(topic,message,{qos: 1},(err) => {
if(!err) {
console.log("主题为"+topic+ "发布成功")
}
})
},
};
</script>