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

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Focus on an empty <input> tag with just the type attribute

In what way can React Testing Library be utilized to isolate a blank <input> element that solely possesses a type attribute? For instance, consider an input field that will eventually have attributes added dynamically, much like the surrounding labe ...

Please refrain from displaying the user table data in the View page source under any script tags

When I access the user data in the script tag of my app.blade.php file, the page resources show this line of code. 'window.user = {"id":2,"name":"test","email":"hidden_email@example.com","email_verified_at":null,"created_at":"2021-03-02T04:52:43.0000 ...

Troubleshooting issue in App component while utilizing React-Redux's 'connect' function

Upon attempting to utilize the connect() function provided by react-redux, I encountered the following error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the r ...

Do external JavaScript files exclusively serve as repositories for functions?

Hey there, I'm a beginner in Web Development and I have a question that might sound silly: If I decide to keep my scripts in an external .js file, would it essentially just serve as a container for functions? For instance, if I attempt to include cod ...

Options for a web-based application that can handle multiple currencies

Looking to create a web application with Vue.js and Firebase that allows users to purchase products or services using a payment API like paypal or stripe. I am trying to display the prices of these products in the local currency of each user, but I'm ...

Under specific circumstances, it is not possible to reset a property in vue.js

In Vue.js, I have developed a 'mini-game' that allows players to 'fight'. After someone 'dies', the game declares the winner and prompts if you want to play again. However, I am facing an issue where resetting the health of bo ...

Leverage the Ajax response within a Jade template

I'm currently utilizing ExpressJS with the Jade template engine. My goal is to achieve the following: Within a Jade file, I need to extract a variable that will be used in a JavaScript file. This JavaScript file will then make an Ajax request to the ...

Using jQuery to loop through a table and retrieve the button value from every row

I have a challenge with dynamically created buttons in a table. My goal is to loop through the table, identify the rows that have a checked checkbox, and retrieve the value of a button within that row. I then need to store these values in an array. Unfortu ...

Enhance Your NextJs Website with Interactive Tooltips using @tippyjs/react

<Link href="/company/add" > <a title="My New Title" data-toggle='tooltip' className="btn btn-primary">My Link</a> </Link> Trying to integrate a Tippy tooltip component with a Nextjs Link do ...

How can I translate these JQuery functions into vanilla JavaScript?

I am currently in the process of building a configurator using transparent images. The image configurator functions through a basic JQuery function: I have assigned each input element a data attribute called data-Image. This function identifies the data-Im ...

Avoid unnecessary renders by only updating state if it has changed from the previous state

Is there a specific React lifecycle method that can trigger a re-render only when the updated state differs from the previous state? For instance, consider the code snippet below: class App extends Component { constructor() { super(); this.state ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

Using either Model or Controller for Vuetify validation

My goal is to implement validation in my Vuetify form, using data from my Model or Controller, and display an alert message. Here is a snippet from my .vue file: <v-row dense> <v-col cols="3"> <v-text-field dense outli ...

Building an instance using an object and an array with Vue.js 2.0

I am working with an array and an object created in Vue.js, and my goal is to combine them into a single 'selection' array following this format: selection[ {food: Chicken, quantity: 3}, {food: Rice, quantity: 2}, {food: Pasta, quantity: 1} ]; ...

Utilizing React to customize JVectorMap markers

Having an issue with a marker appearing in my React project https://i.stack.imgur.com/hkqnZ.jpg The markers are displaying correctly, but there is a persistent initial marker at 0,0 that I can't remove. Removing the 'markers' property from ...

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...

The function "onClick" within an external .js file is being referenced

Just starting to learn Javascript and experimenting with an onClick event for an image in an external .js file using the HTML tag. <script type="text/javascript" src="embed.js"> The code found in "embed.js" is as follows: var image1=new Image(); i ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

JavaScript regular expressions only recognize certain characters

When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include: a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] ! I attempted to use the following regex for validation: var r ...