Vue.js does not show the span element when errors are present

There is an error array in the data that gets populated when a user focuses out of an input field. If the input is empty, it adds an object to the error array with specific messages for 'product_name' and 'barcode'. The structure looks like this:

[
    "0": {
        "product_name": {
            "message": "This field is required"
        },
        "barcode": {
            "message": "This field is required"
        }
    },
    "1": {
        "barcode": {
            "message": "This field is required"
        }
    },
    "2": {
        "product_name": {
            "message": "This field is required"
        }
    }
]

The numbers 0, 1, 2 correspond to the index of the item in a v-for loop, while 'product_name' and 'barcode' refer to the inputs in each item/index. I am now attempting to display these errors.

I have tried the following code snippets but they do not display the span:

<span class="tooltip" 
      v-if="errors && errors[index] && errors[index]['product_name']" style="left: 5px">
  test123 (this is a product_name error)
</span>

<span class="tooltip" 
      v-if="errors && errors[index] && errors[index]['product_name']" style="left: 5px">
  test123 (this is a barcode error)
</span>

An issue might be related to the checkInput function as shown below:

   checkInput(name, itemIndex){
        if(this.documentItems[itemIndex][name] == null){
            this.errors[itemIndex][name] = { message: 'This field is required'}
        };
        //testing
        console.log(this.errors[itemIndex][name]); //works
        if(this.errors[1]['product_name']){
            console.log("yes"); //works
        }
    },

If I define the errors object directly without using a loop, the spans show up correctly:

        errors: {
            0: {
                barcode: '',
                product_name: ''
            },
            1: {
                barcode: '',
                product_name: ''
            }
        },

However, if I create the errors object using a for loop, the spans do not show up:

for(var i = 0;i < response.data.documentItems[0].length;i++){
  this.errors[i] = {
    barcode: '',
    product_name: '',
  }
}

Answer №1

The issue you're facing stems from a particular reactivity quirk in Vue, as outlined in their official documentation.

https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects

Vue automatically creates proxy-like objects for each field defined in your data function before execution. When manually adding fields using this.foo = bar, Vue might not make them reactive if the key 'foo' isn't initially present in your data. Consequently, DOM updates won't reflect changes to these non-reactive fields.

To work around this limitation, there are a couple of approaches recommended by Vue's documentation.

One method, also highlighted in the docs, involves creating a new object with the desired field updates using Object.assign or spread syntax and then reassigning it within the data property.

// Instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })

This solution essentially treats the field as immutable, ensuring proper reactivity.

To rectify issues in your checkInput method, consider implementing the following modification:

   checkInput(name, itemIndex){
        if(this.documentItems[itemIndex][name] == null){
            const newErrorForName = { [name]: { message: 'This field is mandatory' }};
                this.errors = Object.assign({}, {...this.errors, [itemIndex]: newErrorForName })
        };
        // Testing
        console.log(this.errors[itemIndex][name]); // Works fine
        if(this.errors[1]['product_name']){
            console.log("Yes"); // Also works
        }
    },

This is necessary because Vue struggles to handle manual object property additions or deletions.

The alternative approach is to utilize an array structure instead of an object for errors, particularly if errors naturally align with an indexed format. This adjustment could provide a more efficient solution given the fixed integer-based indexes inherent in your errors list.

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

Methods for identifying Flash and guiding the user through installation

When visiting http://www.plupload.com/example_custom.php without flash installed, a popup box is launched: I'm curious about the method they are using to achieve this. Is it through jQuery JavaScript code snippet or another technique? Additionally, ...

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

Transform arrays within arrays to objects

I've been struggling to convert a nested array like the one below: var array = [ [['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf ...

Is it possible for me to retrieve a variable that is contained within a function?

I have extracted data from 2 separate JSON files and now I am looking to divide one by the other. How can this be achieved? Specifically, I aim to divide the 'sugString' with the 'htmlString'. Following this operation, I want to insert ...

Tips on customizing data labels using Jquery Highcharts in column charts

Is there a way to change the positioning of data labels in a column chart? Currently, my data labels appear within the columns, but I'd like to adjust their position. I've tried changing the code below, but nothing seems to work. The colors chang ...

Deselect all checkboxes other than the daily selection

I recently designed an E-commerce website that includes a package customization feature where users can modify their packages. The initial question presents three radio button options: 1. Daily 2. Weekly 3. Monthly If the user selects 'daily&apos ...

Remove an item from an array and keep it stored efficiently without generating unnecessary waste

I'm interested in finding a high-performance method for removing and storing elements from an array. My goal is to create an object pool that minimizes the need for garbage collection calls. Similar to how .pop() and .unshift() remove elements from a ...

NextJS's Server-Side Rendering makes it incompatible with Reactotron

While setting up the redux store for my NextJS application, I usually rely on the Reactotron library to inspect the store. However, since NextJS involves server-side rendering, importing the configuration in the app file results in an error message saying ...

Is it possible to loop through a subset of a collection using *ngFor?

Is it possible to iterate through a specific range of elements in a collection using *ngFor? For instance, I have a group of checkboxes with their form control name and label specified as follows: [{id: 'c1', label: 'C1'}, ...] Assum ...

Comparing AngularJS ng-repeat usage in views with for loop implementation in controllers

Here's a scenario I encountered: I have a complex object and need to iterate through it to perform some arithmetic operations. These values won't be stored in the backend, just for display. Should I use ng-repeat and ng-if in the view, or should ...

I am having trouble with the popstate function in React - it doesn't seem to be working. I am unsure how to trigger the browser backtab click properly. When I click

What is the best way to trigger a logout function in React when the browser back tab is clicked? I am looking for a solution where, upon clicking the back tab, a modal confirmation dialog appears with an "OK" button to log out of the application. const ha ...

Update the color of the text depending on the background color

When hovering over my CTA, a sliding effect occurs. However, I am facing an issue with the text being difficult to read depending on the background color. To better understand what I'm trying to achieve, you can view the demo here: Demo on CodePen T ...

Is it possible to access Firebase data in Vue.js, with or without Vuefire, using a router parameter before the DOM is rendered?

When I navigate to a view from another view, I pass the itemId as a param value to vue router. My goal is to call firebase with that itemId in order to filter the data and use the filtered result/data in the UI. Specifically, I am utilizing vuefire. The ...

What is the process for using a click event to redirect to a different page on a website?

Currently, I am working with vue-bootstrap and I have a set of cards, each containing a button. I want each of these buttons to redirect me to a different form, but I am struggling with implementing this functionality. Below is the snippet of my code: < ...

The AJAX comments triggered an Uncaught SyntaxError due to an unexpected identifier

Can someone assist me in identifying the issue? I keep receiving an Unexpected identifier error when attempting to use ajax for sending comments. Code: function funcSuccess(data) { $("#comment_ajax").text(data); } function funcBefore() { $("#comme ...

Discrepancy in Code Outputs

Last night, I spent some time testing out code for basic functions. To preview my work, I used two platforms - Dash and JSFiddle. Everything seemed to be running smoothly on both sites. However, when I uploaded the code to my live website, none of the butt ...

Retrieve the list of roles within a Discord server using Discord.js (as an array)

Exploring Discord bot development with discord.js I recently delved into the world of Discord bot development using the discord.js library. One specific task I encountered was extracting Guild roles and storing them in an array. After some experimentatio ...

React: Error - Unable to use this.setState as a function

When attempting to pass a value from the Child Class to the Parent Class and set it in the Parent's state, I encounter the following error: TypeError: this.setState is not a function Parent Class class Header extends React.Component { constr ...

Using AngularJS to dynamically modify filter choices

Seeking something similar to this example in the documentation, but with a unique input that can serve as a filter for "any", "name", or "phone" properties. The role switching is triggered by clicking an anchor tag. Check out the code snippet here: http:// ...

Twilio Fax Reception: Blank Body Detected

I have embarked on my journey with Twilio's Programmable Fax API and successfully followed their getting started guide. However, upon receiving the fax, I encounter an issue where the request body appears as an empty object when logged to the console. ...