Using vue.js to assign data within an if statement of a function

I have a Vue form that is set up 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;
                      }
                }

            }
        })

The form works well except for the this.error = aMessage ; part.

When something goes wrong, the aMessage should be displayed in {{error}} on my form, but it doesn't seem to work.

If I manually set this.error = 'test' ; outside of the if statement at the beginning of the login() method, it does work when called.

Similarly, if I just use console.log(aMessage) within the if statement, it also works fine.

I am puzzled as to why setting this.error directly does not seem to work as expected.

Answer №1

The issue lies in the fact that within those functions, the context of `this` does not point to your Vue instance. To resolve this, I recommend reorganizing your functions as shown below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Events related to collisions in Physijs

Two boxes are at play in my scenario. One starts on the ground while the other is dropped on top of it, with gravity turned on. I'm attempting to trigger the collision event listener on the bottom box that rests on the ground, but for some reason, not ...

In what ways can the content of <tr> be switched?

Hey there! I've written a cool little script for toggling the content of a table. The content is hidden inside a <div> with the class "hiddenDiv". In order to reveal it, there is a <span> with the class "toggle" that contains a link. Click ...

Learn how to pass data as props to child components in Vue3

I'm facing an issue where props are initialized, but they disappear after using .mount. Can anyone advise on the correct way to set up props with dynamically loaded components? import {createApp} from 'vue' blockView = createApp(Block); blo ...

Is it possible to adjust the element's position using the code "element.style.top = window.scrollY"?

Recently, I attempted to create a floating input element that would follow the scroll. After much effort, I managed to achieve it and the code is provided below. However, I encountered an issue when trying to change "setText(window.scrollY)" to ...

Retrieve JSON array object values by iterating through each element using $.each

Here is how my JSON data is organized: [{ "industry": [{ "Supermart": [{ "merchant": [{ "name": "Lazada", "banner": "abc.com/img.jpg", "url": "http://lazada.com.my" }] ...

Tips for injecting variables into an .EJS template

On my website, I have an index page, an about page, and a contact page. In addition, there is a header.ejs file that contains the following code: <a href="/">Home</a> | <a href="/about">About Me</a> | <a href="contact">Contac ...

I must utilize the MongoDB native driver to retrieve unique IDs sorted by a timestamp column

I am currently utilizing the nodejs mongodb native driver for developing a chat application. Within my database, I have a collection named dialog which contains fields for sessionId and dateCreated (timestamp). My objective is to retrieve a list of distinc ...

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

Images following do not have jQuery hidden

I am facing an issue with a small test script that is designed to hide images on button click. However, the problem I am encountering is that it only hides the first image out of three and then ceases to hide the subsequent ones. Below is the code snippet ...

Transferring PHP Multidimentional Array data to Javascript

I've scoured this website for a solution, but unfortunately, nothing seems to be working. So, I've decided to reach out to you all for help. I hope you can assist me with my issue. The problem lies within a PHP file that is populating an array w ...

Incorporating an image as a clickable element instead of a traditional button using HTML and

Here's the issue at hand: I currently have "+" and "-" icons at the end of each row to add and delete rows as needed. However, I would like to replace the "-" icon with a trashcan symbol instead. I attempted to do this by replacing it with an image s ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

My discord.js bot remains silent in response to a user's message, even when no errors are present

My Discord bot is using version 13.1.0 of discord.js and my Node version is 16.7.0. I utilized the commands npm init to generate a package.json file and npm install discord.js to install the Discord package. The code for the bot is written in index.js, an ...

Having trouble with sharing feature in React Native for Android and iOS platforms?

I'm having trouble sharing pdf file links or image links in a react native mobile app web browser. I added a share button, but when the user clicks on it, they see options to share via WhatsApp, Gmail, messages, etc. However, when clicking on WhatsApp ...

How to upload an image using Java and store it on a server without the use of Html5

Looking to upload an image file on the server using a servlet without utilizing HTML5. While browsing through stackoverflow, most answers I found were based on PHP. I attempted to read the image file at the client-side in JavaScript with FileReader.readAsD ...

Encountering an Error with JsonRpcProvider while deploying a contract or attempting to run a node

An error has occurred: Error: ERROR processing skip func of /home/dylan/hh-fcc/hardhat-smartcontract-lottery-fcc/deploy/00-deploy-mocks.js: TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider') While following the freecodeca ...

What causes the 'this' to be undefined in React event handlers?

It is common knowledge that in the React code provided, this will be undefined. Various approaches such as binding and arrow functions can solve this issue. What I am interested in is understanding the rationale behind this behavior. Kindly elucidate on ...

What does the cb parameter represent when null in the context of multer?

Why do the cb functions in the code snippet below from the multer API take null as their first argument? What are the implications of using null in this context, and what alternative values could be passed besides null? var storage = multer.diskStorage( ...

AngularJS Vimeo API Request Error: "401 Authorization Required"

I've been experimenting with making external API calls to Vimeo from my AngularJS code using $http.jsonp. However, I keep receiving a 401 Authorization required error even though I have included my authorization key in the header. I encountered a simi ...