简体   繁体   中英

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.

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 ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM