Vue.js 没有得到 mqtt 响应信息

Vue.js does not get mqtt response message

我是 Vue 的新手,对于这个项目,我试图将默认值传递给 Vue data return() 。目前它打印出 console.log('INSIDE CLIENT ON MESSAGE")。但是定义为 this.room1status = 1 的值不会传递或更新为 data return room1status。有没有一种方法可以将值 1 传递给 vue 的 room1status,一旦它进入 client.on('message', function (topic, message) ?

脚本

  data(){
    return{
      room1status: ''
      }
   },

  mounted: function(){
    var mqtt = require('mqtt')
    var client  = mqtt.connect('ws://myUrl/')

    client.on('connect', function () {
      client.subscribe('route_status', function (err) {
        if (!err) {
          client.publish('presence', 'Hello mqtt')
        }
      })
    })

    client.on('message', function (topic, message) {

      var filterData = message;
      var x = JSON.parse(filterData);
      console.log('INSIDE CLIENT ON MESSAGE"); /** prints this out succesfully **/
      this.room1status = 1; /** but this does not get passed or updated to data return room1status **/
    }
 }
on 函数回调中的

this 不引用组件实例,因此您应该在调用该回调之前将 this 分配给变量 vm 然后在其中使用它:

  var vm=this;
  client.on('message', function (topic, message) {

      var filterData = message;
      var x = JSON.parse(filterData);
      console.log('INSIDE CLIENT ON MESSAGE"); 
      vm.room1status = 1; 
    }