线上例子:https://data.avuejs.com/build/1828630631186333697
自定义组件视频教程:https://www.bilibili.com/video/BV1dW421R7f1
自定义组件核心代码(下版本会直接做一个独立组件可直接选择):
<template>
<div class="text">
data:{{data}}
</div>
</template>
<script>
export default{
data(){
// mqtt连接账号在这里创建:https://iot.javablade.com/iot/mqtt/account
return{
params:['LightSwitch'],
check:null,
time:500,
productKey:'JkerjK97oub',
deviceName:'HqDHKmXjVGD2yMVn',
config:{
clientId:new Date().getTime(),
username:'bladexiot',
password:'bladexiot',
connectTimeout: 5000
},
url:'wss://broker.javablade.com',
data:[],
client:null
}
},
created(){
this.client = mqtt.connect(this.url, this.config);
console.log(this.url,this.config);
this.client.on('connect', () => {
console.log('mqtt链接成功')
this.onSubscribe();
// 监听消息
this.onMessage();
//循环监听
this.onListen();
})
},
methods:{
getTopicPrefix () {
const prefix = "/blade/sys";
return `${prefix}/${this.productKey}/${this.deviceName}/`;
},
onListen () {
this.params.forEach(ele => {
this.check = setInterval(() => {
if (this.client.connected == true) {
this.sendProperty({ identifier: ele })
} else {
clearInterval(this.check)
}
}, this.time)
})
},
sendProperty (data) {
let topic = this.getTopicPrefix()+'thing/service/property/get';
const req = {
id: new Date().getTime(),
version: '1.0',
params: {
...data
}
};
const message = JSON.stringify(req);
this.publish(topic, message);
},
publish (topic, message) {
this.client.publish(topic, message, (err) => {
if (err) {
console.log(err)
}
});
},
onSubscribe () {
// 设备响应云端获取设备属性
this.client.subscribe(this.getTopicPrefix() + "thing/service/property/get_reply", function (err) {
if (!err) {
console.log('ServicePropertyGetReply 订阅成功');
} else {
console.log('ServicePropertyGetReply 订阅失败', err);
}
});
},
onMessage () {
// 接收订阅消息
this.client.on('message', (topic, message) => {
if (topic ===this.getTopicPrefix() + "thing/service/property/get_reply") {
// 设备响应云端获取设备属性
const data=JSON.parse(message.toString());
this.data=data.params
}
})
}
}
}
</script>
<style>
.text{
color:#fff;
font-size:30px;
}
</style>
演示功能:
在Vue3的版本实例代码工作正常,但是在Vue2版本中提示找不到mqtt
扫一扫访问 Blade技术社区 移动端