Packy Packy - 2 months ago 17
Javascript Question

vue.js set data in if statement of function

I have a form that runs of Vue that looks like this:

new Vue({
el: '#login-container',
data: {
firstname: '',
lastname: '',
email: '',
birthday: '',
signupEmail: '',
password: '',
signupPassword: '',
confirm: '',
error: '',
},
methods: {

login(){

CH.INSTANCE.Services.Login(this.email, this.password, login_onComplete, login_onCancel);

function login_onComplete(aUser)
{
window.location.href = '/';
}

function login_onCancel(aMessage)
{
this.error = aMessage ;
}
},

signup(){

CH.INSTANCE.Services.CreateAccount(this.firstname,this.lastname,this.signupEmail, this.signupPassword,'83835', 'male',this.birthday,':checked',onRegister_onComplete,onRegister_onError);

function onRegister_onComplete(aUser)
{
window.location.href = '/';
}

function onRegister_onError(aMessage)
{
this.error = aMessage;
}
}

}
})


It works fine minus the the
this.error = aMessage ;
.

aMessage
will contain the error message that should be dumped in {{error}} on my form if something goes wrong. The issue is it does get set.

If I set
this.error = 'test' ;
outside the
if
at the beginning of the
login()
method with works when its called.

If I just do
console.log(aMessage)
in the
if
that works as well.

Not sure why it does work when its set.

Answer

The problem is that within those functions, this does not refer to your Vue instance. I would set up your functions like this:

login() {
  CH.INSTANCE.Services.Login(this.email, this.password, this.login_onComplete, this.login_onCancel);
},
login_onComplete(aUser) {
  window.location.href = '/';
},
login_onCancel(aMessage) {
  this.error =  aMessage ;
}
Comments