I trying to do a MQTT connection with Paho in vue.js, but I have some problems with the options object.
Vue.component('componente', {
template: `<div></div>`,
data: () => ({
mqtt: null,
options: {
timeout: 3,
onSuccess: () => this.success(), //here is the problem
onFailure: () => this.failure(),
},
host: "10.0.0.11",
port: 8083,
client: "WebClient",
topic: "mqtt"
}),
methods: {
success: () => {
console.log("Conexion completa");
this.mqtt.subscribe(this.topic);
},
failure: (msg) => {
console.log("error");
console.error(msg);
},
message(msg){
console.log("Mensaje " + msg.payloadString);
},
connect(){
console.log("conectando");
this.mqtt = new Paho.MQTT.Client(this.host,this.port,this.client);
this.mqtt.onMessageArrived = this.message;
this.mqtt.connect(this.options);
}
},
mounted () {
this.connect();
}
});
This do nothing, the success
method is never called. But if I change, .connect
for this, is work.
this.mqtt.connect({onSuccess: () => {this.mqtt.subscribe(this.topic)}});
Previously, I had many problems calling the function on data, gave me errors like "success is not a function". Now, this not show any error.
Edit: The next code work, but the subscribe function do nothing
this.mqtt.connect({onSuccess: this.success});
Simply change data
to not use an arrow function, ie
data () {
return {
mqtt: null,
options: {
timeout: 3,
onSuccess: () => this.success(),
onFailure: () => this.failure(),
},
host: "10.0.0.11",
port: 8083,
client: "WebClient",
topic: "mqtt"
}
}
None of your methods should be using arrow functions either. Make them all normal object methods.
methods: {
success () {
console.log("Conexion completa");
this.mqtt.subscribe(this.topic);
},
// etc
}