Exploring methods to access the state of a component nested within a slot in Vue

I'm facing a challenging issue that I can't seem to solve 🤔. I would really appreciate hearing your thoughts on this problem.

Here's the scenario: I have developed reusable Form and InputField components. The InputField component receives a validation prop, which is a function that determines whether the input is valid or not by returning true or an error message.

// InputField.vue
const validate = () => {
  isValid.value = props.validation(inputValue.value);
};

// App.vue
<InputField
  v-model="formData.firstName"
  element="input"
  required
  name="First Name"
  :validation="(val) => /^.{2,}$/.test(val) || 'Minimum 2 characters'"
/>

Now, in the Form.vue component, I have a variable called isValid. If it's false, the submit function should not work.

So here's where I'm stuck: How can I check the states of all the InputFields within the Form component (which are passed as slots) to determine if isValid is true for each input? Once I can verify that, I need to ensure all inputs are valid before submitting the form.

I'm searching for an efficient solution that will work seamlessly for multiple forms and inputs placed in different parts of the app. I'm not looking for a quick fix.

If you want to dive deeper into the issue, you can access the application through this link: https://codesandbox.io/s/muddy-sun-0ti9m. Feel free to explore and understand the problem better :)

To recap, my main objective is to verify all inputs based on their respective validation functions. Only when all inputs are valid, the Form should be allowed to submit.

Thank you all for your help!

Answer â„–1

I have made some adjustments to the code you provided. You can see the changes in this codesandbox. What I did was allow your InputFields to emit a unique id, such as 'firstname' in my example, along with their validation status. This is achieved by adding a function called checkValidation and including the emit in their implementation using

@check-validation="checkValidation"
.

A new object has been introduced to manage multiple validation statuses. This object can be dynamically created in the future to make the process more generic. Here is the object:

const formValidationObject = reactive({
   firstname: false,
   lastname: false
});

The checkValidation function is structured like this:

const checkValidation = (object) => {
   formValidationObject[object.data.id] = object.data.valid === true;
};

This function receives an object containing the id (e.g., 'firstname') and the validation status. The corresponding key in the formValidationObject will be set to true if object.data.valid is true, otherwise it will be set to false.

You can now pass this as a prop to your Form.vue component and handle any validation issues accordingly.

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

Currently in the process of transitioning to vue3 with <script setup>, encountering issues with the functionality of computed

I recently migrated my Vue2 script to Vue3 using <script setup>. However, I am facing an issue where the computed function does not work even when seriesData is changed. Currently, my source code looks like this and it is functioning correctly: < ...

What is the best way to integrate JavaScript into an Express Handlebars template using partials?

In my current project, I have utilized the following handlebars template (located under views/layouts/main.handlebars): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{title}}</title> ...

Utilize the browser's back button when navigating pages that have been loaded through Ajax technology

$(document).ready(function () { $('#gnav a').click(function (e) { e.preventDefault(); $('#contents').load(this.hash.substr(1) +'.php') }); }); Here is the jQuery code I have written to load content into a ...

Guiding a WordPress Form Submission to a Different Page

I'm currently using WordPress to create a form with the following code: [contact-form][contact-field label='What message would you like to send?' type='textarea' required='1'/]Word Limit: 50 words[contact-field label=&ap ...

The filter function in Material UI data grid does not seem to be functioning properly when using the renderCell method

I'm currently working on a react project that includes a Data Grid. While the filter functionality works well with most fields, it seems to be having issues with the field that utilizes renderCell. Is there a way to enable filtering for the movie titl ...

Encountered an issue while attempting to load the required module

I'm having trouble setting up Stripe for my app and getting errors when trying to implement the module. Typically, I would require the module at the top of the file in order to use it, but when I do this in the paymentCtrl file, it doesn't work a ...

Retrieve Files with Angular Framework

I'm looking to implement a file download or view button using Angular without making a call to the backend. The file is static and the same for all users, so I want to avoid unnecessary server requests. Many solutions involve using the "download" att ...

AngularJS: The image loader will display on the initial div

I am trying to implement a loader that will hide after a certain amount of time when the user clicks on a profile. I have used a timeout function to achieve this behavior. However, the loader is appearing on the left side instead of within the respective ...

Create a time of 00:19:59 using JavaScript

I am attempting to display a countdown timer that starts at 20 minutes in the format (00:20:00) using setInterval. Once the countdown is finished, it should display as (00:00:00), but I am having trouble achieving this. <body onload = "onloadFunc();" ...

Is Next.js Dynamic Routing Failing You?

Recently, I attempted to implement Dynamic routing for a recipe app but encountered an issue where the page was not found. This problem has left me puzzled as I am fairly inexperienced with TypeScript, although not with React. // pages/recipes/[recipeId].t ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

What is the best way to deliver hefty files to users? Utilize the node-telegram-bot-api

bot.sendDocument(id, 'test.zip'); I am facing an issue while trying to send a 1.5GB file using the code above. Instead of being delivered to the user, I receive the following error message: (Unhandled rejection Error: ETELEGRAM: 413 Request En ...

Struggling to see the Vuetify 'v-select' component on the screen

Welcome to my personal website <template> <v-form> <v-select outlined label="Select a segment from the AI/ML model" :items="options"> </v-select> <v-text-field label="Enter User ID" required>&l ...

What is the best way to add methods to underscore without making them available globally?

Have you added multiple methods to underscore within your package? _.mixin({ foo: function() {}, bar: function() {} //etc }); If you're concerned about potential conflicts with the main application or other packages, what's the best way ...

Exploring Vue 3 and Pinia: Achieving Reactivity in Stored Values

Currently, I am working on a project using Vue 3 with the Composition API and Pinia. Within my application, I have an auth store that retrieves the default email and password values from the store. import { useAuthStore } from "stores/auth"; const authSto ...

Creating pages or tabs within a table using HTML5 and Angular is a simple and effective way to organize

I have a REST response that returns around 500 records. These records are being displayed in an Angular table. I would like to add customization options for the user, allowing them to choose to display 10/20/30... records per page. Additionally, I want to ...

Hovering over objects in Three.js does not function as effectively as clicking on them

Just getting into Three.js I'm attempting to load a GLTF model and add mouseover and mouseout events. The goal is for the color of the GLTF model to change on mouseover and revert back to the original on mouseout. I have had some success with this, ...

Error in Javascript: Required variable missing for Sendgrid operation

I am facing an issue while attempting to send an email using sendgrid. Whenever I execute the function, it gives me an error saying "Can't find variable: require". Despite my efforts to search for a solution online, I have not been able to resolve thi ...

React Native does not support Laravel Echo's listenForWhisper functionality

I have successfully implemented private channels and messaging in my Laravel App using websockets:serve. Now, I am attempting to enable whisper functionality for the typing status but encountering some issues. When sending a whisper: Echo.private('c ...

Similar to LINQ's Enumerable.First(predicate) method but with a slightly different syntax, this

When working with JavaScript, we often encounter situations where we need to find the first matching element based on certain conditions. Take for example this code snippet: function process() { var firstMatch = ['a', 'b', 'c&ap ...