在Vue中使用MQTT

1.脚手架中安装mqtt

npm install mqtt --save

官方有一个例子:

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
  client.subscribe('presence', function (err) {
    if (!err) {
      client.publish('presence', 'Hello mqtt')
    }
  })
})
client.on('message', function (topic, message) {
  // message is Buffer
  console.log(message.toString())
  client.end()
})

1.在vue文件中引入mqtt

import mqtt from 'mqtt'

2.在data中声明client对象

data() {
    return {
      mtopic: "1101",
      msg: "",
      client: {}
    };
  }

3. 在mounted钩子中建立连接

mounted() {
    this.client = mqtt.connect("ws://ip:port", {
      username: "admin",
      password: "password"
    });
    this.client.on("connect", e =>{
      console.log("连接成功");
      this.client.subscribe(this.mtopic, (err) => {
        if (!err) {
          console.log("订阅成功:" + this.mtopic);
        }
      });
    });
    this.client.on("message", (topic, message) => {
      this.msg = message
    });
  }

4. 可以把发布消息函数写到methods里面

methods: {
    handleclick: function() {
      this.client.publish(this.mtopic, this.msg);
    }
  }

最后贴上完整代码

<template>
  <div class="hello">
    <h1>收到的消息:{{msg}}</h1>
    <button @click="handleclick">发布</button>
  </div>
</template>

<script>
import mqtt from "mqtt";
export default {
  name: "HelloWorld",
  data() {
    return {
      mtopic: "1101",
      msg: "lalala",
      client: {}
    };
  },
  mounted() {
    this.client = mqtt.connect("ws://ip:port", {
      username: "admin",
      password: "password"
    });
    this.client.on("connect", e =>{
      console.log("连接成功");
      this.client.subscribe(this.mtopic, (err)=> {
        if (!err) {
          console.log("订阅成功:" + this.mtopic);
        }
      });
    });
    this.client.on("message", (topic, message) => {
      this.msg = message
    });
  },
  methods: {
    handleclick: function() {
      this.client.publish(this.mtopic, this.msg);
    }
  }
};
</script>

转自:https://blog.csdn.net/m0_37811924/article/details/102602914

猜你喜欢

转载自www.cnblogs.com/Strangers/p/13377346.html