Setting a Vue child component class directly from its parent component

In my Vue component, I have multiple child components that are inputs of the same type. The number of inputs can vary depending on the user, but there is a rule that at least one input must be filled. For example, there could be 5 inputs with 4 of them empty and still considered valid.

My issue is that I want to highlight the first input in red if all inputs are empty. I am checking the inputs in the parent component.

Here is a snippet of the parent component code:

<template>
    <custom-input v-for="(input, key) in inputs_num" :key="key" />
</template>

<script>
    data() {
        return {
            inputValues: [],
            inputs_num: 1
        }
    }
    methods: {
        checkInputs() { 
            const validInputsCounter = 0;
            this.inputValues.forEach((input) => {
                if(input.trim().length > 4) validInputsCounter++;
            });

            if(validInputsCounter == 0) {
                // Add border to the first input in the list.
            }
        }
        ...
        ...
    }
</script>

I am struggling to figure out how to apply the border to only the first input in the list.

Answer №1

It is recommended to pass the highlight state as a prop on the child component.

<template>
    <custom-input v-for="(input, key) in inputs_num" :key=key" :highlight="isInputHighlighted(key)"/>
</template>

<script>
    data() {
        return {
            inputValues: [],
            inputs_num: 1
        }
    }
    methods: {
        isInputHighlighted(key){
            if(key == 0){
                if(this.inputValues.find(i => i.trim().length > 4) != undefined){
                    return true;
                }
            }
            return false;
        }
    }
</script>

Then in your child component, declare a "highlight" prop with a default value of "false". If there is an <input> element in that template, you can apply the class like this:

<input type = "text" :class="{'red-border':highlight}" ... />

Code not checked for validity. Syntax error hunting is left as an exercise for the reader.

Answer №2

If you're looking for an example, you could consider implementing the following code snippet:

<template>
    <custom-input v-for="key in inputValues.length" :key="key" v-model.trim="itemValues[key - 1]" :class="{red_border: key==1 && allEmpty}" />
</template>

<script>
export default
{
    data() {
        return {
            inputValues: [],
        }
    },
    computed:
    {
      allEmpty()
      {
        return !this.inputValues.some(item => (item || '').trim().length > 4);
      }
    }
}
</script>

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

Center-aligned footer with a sleek right border in Bootstrap 4.1.1

Presenting my design concept for the footer: https://i.sstatic.net/kxdXJ.png Here is the code snippet for the footer design utilizing Bootstrap 4.1.1: .mainfooter-area { background: #404044; padding: 100px 0; } ... <link href="https://cdnjs.cl ...

Is the behavior of undefined different in Chrome?

Upon examining my Asp masterpage, I noticed the following code snippet: <script> if (theForm !== undefined) { // <<== line 746: error theForm.onsubmit = ...bla bla... ; } </script> When checking the Chrome console, an er ...

The background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

Creating a form that can identify both letters and numbers using JavaScript

Is it possible to create an <input> field that can recognize both letters and numbers while disregarding spaces and capitalization? Here is my current progress, aiming for the feedback to display as "right" when 9 H 6 U 8 f is entered in the field, ...

CrossBrowser - Obtain CSS color information

I'm attempting to retrieve the background color of an element: var bgcolor = $('.myclass').first().css('background-color') and then convert it to hex function rgbhex(color) { return "#" + $.map(color.match(/\b(\d+ ...

The ajax POST method fails to trigger in a Node.js environment

Having an issue with the POST request. It's necessary for updating info without page reload. Below is my pug code: .tinder--buttons form(id="form1") button#love(type="submit") i.fa.fa ...

What prevents certain scenarios from being encapsulated within a try/catch block?

Just attempted to handle ENOENT by using a naive approach like this: try { res.sendFile(path); } catch (e) { if (e.code === 'ENOENT') { res.send('placeholder'); } else { throw e; } } Unfortunately, this method is ineffectiv ...

JavaScript function encountered an error due to an expected object

Currently, I am in the process of developing an application using VS2015, JavaScript, Angular, and MVC 5. Here is an excerpt of my JavaScript code: var myApp = angular.module('QuizApp', []); myApp.controller('QuizController', [&apos ...

Choosing between Vue.prototype, Vue.use, and import for each fileWhen it comes

Discover various techniques for implementing a global function in a Vue.js project: time.js // Option 1: if using Vue.use() export default { install: Vue => { Object.defineProperty(Vue.prototype, "time", { return new Date().getT ...

Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided? Fo ...

The concept of localStorage is not recognized in the next.js framework

Currently working with next.js for frontend development. Facing an issue where I need to access user data from localStorage, but due to next.js being a server-side rendering framework, I am unable to retrieve data from localStorage. How can I solve this pr ...

What is the correct way to utilize JSON with AJAX?

I am looking to transfer data from a php backend to a browser using JSON. I have a basic understanding of the process and have included an example code snippet below. However, I have been advised that this may not be the most efficient approach. Due to my ...

The function Array.map is unavailable, causing the datalist to not update as expected

I've been closely following a tutorial series on YouTube, but I keep encountering an error during the process. The link to the tutorial is available here: https://www.youtube.com/watch?v=re3OIOr9dJI&t=11s&ab_channel=PedroTech. The purpose of ...

Combining two-digit values

As a newcomer to JavaScript, I've been working on creating a basic calculator to practice my skills. However, I've run into an issue. When entering a double-digit number, the calculator is adding the digits together instead of treating them as se ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

Access the OpenWeatherMap API to retrieve the weather forecast for a single time slot within a 5-day period

Utilizing the openweathermap api, I am retrieving a 5-day/3-hour forecast here. The API call provides multiple results for each day with data available every 3 hours. For the full JSON response, you can access it here. Please note that the API key is only ...

Can dark mode be activated and maintained across multiple pages using just one JavaScript file?

I'm facing an issue with maintaining a dark mode across multiple web pages. I tried adding a JavaScript script to all my HTML files, but it didn't work as expected. Then, I experimented by adding the script to just one HTML file, and while it suc ...

step-by-step guide on transferring the text content of an HTML paragraph element to another HTML paragraph element through JavaScript in ASP.NET

I'm looking for help with passing the text value from one HTML paragraph element to another when a JavaScript function is called. The function loads a div element with an enlarged image and a paragraph content. Below is the code I am using: JavaScrip ...

Are HTML's Regular Expressions the Equivalent of JavaScript's Regular Expressions?

I have been trying to utilize the pattern="" attribute in HTML to implement regex, but unfortunately, I am unable to locate a comprehensive list of HTML regex parameters. This has led me to ponder whether the syntax for regex in HTML is similar to JavaSc ...

Utilizing Page Methods

I have encountered an issue while using an ajax callback for a void method. When I try to call another method within the calling method, I get an error. Any assistance with resolving this problem would be greatly appreciated. Here is the code snippet: ...