在 Vuejs 中调用数据内部的方法
Call a method inside data in Vuejs
我试图在 vue.js 中与 Paho 建立 MQTT 连接,但选项对象存在一些问题。
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();
}
});
这什么都不做,永远不会调用 success
方法。但是如果我改变,.connect
就可以了。
this.mqtt.connect({onSuccess: () => {this.mqtt.subscribe(this.topic)}});
以前,我在调用数据函数时遇到了很多问题,出现了诸如“success is not a function”之类的错误。现在,这没有显示任何错误。
编辑:下一个代码有效,但订阅函数什么都不做
this.mqtt.connect({onSuccess: this.success});
简单的把data
改成不使用箭头函数,即
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 你的方法也应该使用箭头函数。使它们成为所有普通的对象方法。
methods: {
success () {
console.log("Conexion completa");
this.mqtt.subscribe(this.topic);
},
// etc
}
我试图在 vue.js 中与 Paho 建立 MQTT 连接,但选项对象存在一些问题。
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();
}
});
这什么都不做,永远不会调用 success
方法。但是如果我改变,.connect
就可以了。
this.mqtt.connect({onSuccess: () => {this.mqtt.subscribe(this.topic)}});
以前,我在调用数据函数时遇到了很多问题,出现了诸如“success is not a function”之类的错误。现在,这没有显示任何错误。
编辑:下一个代码有效,但订阅函数什么都不做
this.mqtt.connect({onSuccess: this.success});
简单的把data
改成不使用箭头函数,即
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 你的方法也应该使用箭头函数。使它们成为所有普通的对象方法。
methods: {
success () {
console.log("Conexion completa");
this.mqtt.subscribe(this.topic);
},
// etc
}