A guide on updating data dynamically in Vue.js

I am facing an issue with Vue JS in my frontend development. Here is the data for my component -

data: () => ({
        email: "",
        showError : false
    }),

Below is the corresponding HTML code -

<div v-show='showError' class='errorBox'>
    <p>Error</p>
</div>

The problem I am encountering is that I am unable to dynamically change the value of showError in the data. Despite writing the following code, the value does not update and no error is shown in the console:

axios.get('/accounts/passwordresetpage_ajax_validation/' + '?email=' + email.value)
.then(function (res) {
                        if (res.data.email_does_not_exists) {
                            return this.showError = true
                        } else {
                        document.querySelector('form').submit()
                            
                        }
                    });

This code snippet is contained within a component method. Any assistance on resolving this issue would be greatly appreciated.

Answer №1

As mentioned by @punund, the usage of this here does not point to the specific component where the data property is connected. In this scenario, the context revolves around the callback function. To tackle this, there are a few approaches you can take. One option is to employ a variable to store a reference to this

const self = this;
axios.get('/accounts/passwordresetpage_ajax_validation/' + '?email=' + email.value)
  .then(function (res) {
    if (res.data.email_does_not_exists) {
      self.showError = true
    } else {
      document.querySelector('form').submit()
    }
  });

You also have the choice to utilize the bind method to generate a function with the vue component's context

axios.get('/accounts/passwordresetpage_ajax_validation/' + '?email=' + email.value)
  .then(function (res) {
    if (res.data.email_does_not_exists) {
      this.showError = true
    } else {
      document.querySelector('form').submit()
    }
  }.bind(this)
  );

In my view, and the most seamless method to make use of the this keyword in relation to the vue component is through the ES2015 arrow function

 axios.get('/accounts/passwordresetpage_ajax_validation/' + '?email=' + email.value)
  .then((res) => {
    if (res.data.email_does_not_exists) {
          this.showError = true
    } else {
      document.querySelector('form').submit()
    }
  });

If you wish to delve deeper into this topic, check out this informative post.

On the flip side, if videos are more your style, consider watching the following educational Youtube video that delves into explaining contexts effectively.

Answer №2

this within the context of .then(function (res) may not refer to what you expect. To access data directly, try this:

axios.get('/accounts/passwordresetpage_ajax_validation/' + '?email=' + email.value)
.then(function (res) {
                        if (res.data.email_does_not_exists) {
                            return data.showError = true
                        } else {
                        document.querySelector('form').submit()
                            
                        }
                    });

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

What are the best methods for creating genuinely random and highly secure session IDs?

I am looking to develop session middleware for Express, however, I am unsure about generating random and secure session IDs. How do larger frameworks like Django and Flask handle this issue? What would be the best approach for me to take? ...

Ensure that this specific attribute remains responsive by either setting it within the data option or initializing it for class-based components. Vuex is another viable option to consider for managing state

Terminal Error in vue.runtime.esm.js:4573 [Vue warn]: The property or method "setRegisterEmail" is not defined in the instance but referenced during rendering. Please ensure that this property is reactive, either in the data option, o ...

Create a named scopedSlot dynamically

Looking to incorporate the following template into my component's render function, but struggling with how to do so. This is the current template structure: <template> <div> <slot name="item" v-for="item in filte ...

Encountering unanticipated undefined elements while incorporating map in JSX

I'm attempting to dynamically generate <Audio> components using the map method: import React, { useState, useRef, createRef } from 'react'; const audios = [{ src: '/fire.mp3' }, { src: '/crickets.mp3' }]; function ...

At the beginning of the application, access the Ionic Secure Storage using the get() method

I am facing an issue with retrieving a token for validating an Auth status in the /src/main.ts file: if (TokenService.getAccessToken() !== undefined) { ... } Here is my token.service.ts file: import storage from '@/plugins/storage' const ACCESS ...

Tips for submitting multiple radio button values in a tabular format

HTML Code: <div class="tab"><h4>Zip Code</h4> <p><input type="text" class="text1" placeholder="Enter zip code..." oninput="this.className = ''" name="zipcode"></p> </div> <div class="tab">& ...

Maintain the expanded sub-menu when the mouse leaves the area, but a sub-option has been

Implementing a side menu with parent and child options that dynamically display content in the main div on the right when a child option is selected. The parent options are initially shown upon page load, and the child options appear when the mouse hovers ...

Adjust the overflow to automatically decrease at regular intervals

Is there a way to make the scroll automatically move down a bit every few seconds, revealing more text in the process? Here's an example of how I want it to work: http://jsfiddle.net/Bnfkv/2/ ...

Can Jquery be used to swap out specific li content?

<div class="widget_ex_attachments"> <ul> <li> <i class="fa fa-file-word-o"></i> <a href="uploads/2014/09/Parellel-universe.docx">Parellel universe</a> </li> ...

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Tips for incorporating <ios> or <android> components into your Nativescript Vue project

Can someone help me with this issue? <android> <NavigationButton text="Go Back" android.systemIcon="ic_menu_more" @tap="$refs.drawer.nativeView.showDrawer()"/> </android> ...

Having trouble sending JSON data to Vue.js

While the code snippet below works perfectly fine with mounted function, pushing data to "infox" without any issues. <script> export default { data() { return { infox: null, dino: d_var } }, mounte ...

Create a form action dynamically with JavaScript

html code : <section class="main"> <form class="form-4" name="form4" id="form4" method="POST"> <p class="submit"> <button type="submit" name="submit" onclick="show()"><i class="icon-thumbs-up icon-large"></i> ...

Illuminate the current page

I have been working on a website with around 20 pages that all have a side navigation bar. To make it easier to manage, I decided to centralize the links in a JavaScript (JS) file and include it on each HTML page. This way, any changes can be made quickly ...

A guide on extracting the current website URL in a React application

I wanted to find a method to duplicate the text from a URL so that users could easily share the link with others. ...

Exploring Vuetify: Navigating Through Sub-Menus on a Drawer

My goal is to create a navigation drawer with expandable sub-menus for specific options. For example, the main menu option "User Profile" may have sub-menus like "Update Contact Details" and "Review Registration". I've experimented with different app ...

What is the most efficient way to enable seamless communication between sibling components in Vue.js 2?

Just starting out with Vue.js 2 and I'm really enjoying it so far despite being new to it. Currently using the latest version. I've begun working on my first larger application and ran into a scenario right off the bat where I have a main app co ...

Having trouble locating the mongoDB module while trying to deploy on Heroku

After deploying my node.js server to Heroku, I encountered the following error message: 2018-12-27T10:10:28.370131+00:00 app[web.1]: Error: Cannot find module './lib/utils' 2018-12-27T10:10:28.370137+00:00 app [web.1]: at Function.Modul ...

`There was an error in require.js stating that the property '$' of object #<Object> is not a function.`

Recently, I decided to give require.js a try for the first time, but unfortunately, I encountered an error that left me puzzled: Uncaught TypeError: Property '$' of object # is not a function. require.config({ shim: { "jquery" ...

Distinct elements within a JavaScript hash

Is there a jQuery method to add a hash into an array only if it is not already present? var someArray = [ {field_1 : "someValue_1", field_2 : "someValue_2"}, {field_1 : "someValue_3", field_2 : "someValue_4"}, {field_1 : "someValue ...