index.html中引入mqtt文件  <script src="./js/mqttws31.min.js" type="text/javascript"></script>

vue 文件中使用

data(){

  return{


    topic:"message-topic",


    color:""


  }

}



 mounted(){


    this.MQTTconnect();


  },



methods:{



 //实时通信


    MQTTconnect() {


      const host = '192.168.x.xx';


      const port = xxxx;


      this.mqtt = new Paho.MQTT.Client(  //实例化一个对象


        host,


        port,


        "client" + this.getuuid(),  //防止多个浏览器打开,导致的问题,保证唯一性


      );


      var options = { 


        timeout: 10,


        useSSL: false,


        cleanSession: false,


        //如果为false(flag=0),Client断开连接后,Server应该保存Client的订阅信息。如果为true(flag=1),表示Server应该立刻丢弃任何会话状态信息。


        onSuccess: this.onConnect,


        onFailure: function(message) {


          //连接失败定时重连


          setTimeout(this.MQTTconnect, this.reconnectTimeout);


        }


      };


      this.mqtt.onConnectionLost = this.onConnectionLost;


      this.mqtt.onMessageArrived = this.onMessageArrived;


      //用户名和密码的验证,我这里都为空;不加验证


      const username = "admin"


      if (username != null) {


          options.userName = 'admin';


          options.password = '123';


      }


      this.mqtt.connect(options);


    },


    //uuid随机生成


    getuuid() {


      var uid = [];


      var hexDigits = "0123456789abcdefghijklmnopqrst";


      for (var i = 0; i < 32; i++) {


          uid[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);


      }


      uid[6] = "4";


      uid[15] = hexDigits.substr((uid[15] & 0x3) | 0x8, 1);


      var uuid = uid.join("");


      return uuid;


    },


    //连接


    onConnect() {


  console.log("onConnected");


      //连接成功,发送信息,信息内容为12354654788



  // this.mqtt.send(this.send_topic, "12354654788", 0);


 


    //连接成功,订阅信息


      this.mqtt.subscribe(this.topic);


    },


    //连接丢失


    onConnectionLost(response) {


        console.log("异常掉线,掉线信息为:" + response.errorMessage);


    },


    //接收到消息,处理


    onMessageArrived(message) {


      console.log(message)


        var topics = message.destinationName;


        var msg = message.payloadString;


        // console.log(msg)


        //判断主题,调用方法,这里可以订阅多个主题,在此处判断,接受不同的主题,调用不同的方法!


        if (topics == this.topic) {


          //添加


         this.color = msg


        }else {


          return;


        }


    },


}