<template> <div id="app"> <top/> <router-view/> </div> </template> <script> import top from '@/components/top.vue' import mqtt from "mqtt/dist/mqtt" import {getDeviceByCode} from "@/api/resultApi"; export default { name: 'Home', components: { top }, data() { return { client: null, code: '' }; }, created() { this.load() }, methods: { load() { // 获取名为id的查询参数值 if (this.cite.code === "") { this.code = this.$route.query.code; this.cite.code = this.code; }else{ this.code = this.cite.code; } console.log(this.code); // 输出查询参数的值 this.initMqtt() if (this.cite.facility === "") { this.getDeviceByCode(); } }, initMqtt() { // 连接配置选项 let options = { connectTimeout: 4000, // 超时时间 // 认证信息 clientId: '', //不填默认随机生成一个ID username: 'admin', //用户名 password: 'public' //密码 } this.client = mqtt.connect('tcp://192.168.250.29:8083/mqtt', options) //调用连接的api //连接成功 this.client.on('connect', (e) => { console.log('连接成功', e) this.subscribes() }) //重连提醒 this.client.on('reconnect', (error) => { console.log('正在重连', error) }) //连接失败提醒 this.client.on('error', (error) => { console.log('连接失败', error) }) //接收消息 this.client.on('message', (topic, message) => { const data = JSON.parse(message) //接受到控制信号的数据 console.log(data) if(data.login) { this.cite.memberLoginVo = data.memberLoginVo }else{ this.cite.memberLoginVo = '' } }) }, //订阅多个主题 subscribes() { const arr = ['/tzdy/send/device/'+this.code] this.client.subscribe(arr, { qos: 0 }, (err) => { if (!err) { console.log(`消息订阅成功`) } else { console.log('消息订阅失败') } }) }, getDeviceByCode() { getDeviceByCode({ code: this.code }).then((res) => { this.cite.facility = res.data; }); }, } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } * { margin: 0; padding: 0; } body { background: #FAFAFA; } .flex-center{ display:flex; flex-direction: row; align-items:center; justify-content:center; } .flex-start{ display:flex; flex-direction: row; align-items:center; justify-content:flex-start; } .flex-end{ display:flex; flex-direction: row; align-items:center; justify-content:flex-end; } .flex-between{ display:flex; flex-direction: row; align-items:center; justify-content:space-between; } </style>