Top recommendations for integrating a customized form in Vue

My objective is to develop a unique custom form component named app-form, which offers the capability of using v-model for validation access. The input will be utilizing another custom component called app-input.
Here's the progress I've made so far.

app-form

<template>
  <div>
    <slot></slot>
  </div>
</template>
const acceptedTags = ['app-input'];
export default {
  /*
  props: value,
  data: isValid
  */
  updated() {
    // update isValid whenever the view changes
    this.checkValidation();
  },
  methods: {
    checkValidation() {
      this.isValid = true;
      this.checkValidation(this);
      this.$emit('input', this.isValid);
    },
    checkValidationRecursion(node) {
      if (acceptedTags.includes(node.$options.name)) {
          let result = node.checkValidation();
          this.isValid &&= result;
      }
      node.$children.forEach((child) => this.checkValidationRecursion(child));
    },
  }
}

app-input

<input
  :value="selfValue"
  @input="onInput"/>
export default {
  name: 'app-input',
  /*
  props: value,
  data: selfValue,
  */
  methods: {
    checkValidation() {
      let valid = true;
      /*
        this.rules = [(v) => !!v || 'Required'];
      */
      for (let f of this.rules) {
        let result = f(this.selfValue);
        if (typeof result === 'string') {
          valid = false;
        }
      }
      return valid;
    },
    // onInput() => update selfValue and emit
  },
  // watch: update selfValue
}

In the provided code snippet, the app-form needs to traverse the entire component tree to locate the desired inputs each time there is an update. Are there more efficient approaches to accomplish this task?

Answer №1

When dealing with these types of scenarios, I find it beneficial to utilize provide/inject https://v2.vuejs.org/v2/api/#provide-inject. The concept involves "providing" an object in a Parent-Component (such as your Form-Component) and then "injecting" this object into any descendant Components. Although the data is not reactive by default, you have the option to pass a reference to a reactive Object (e.g., a Vue Object).

In cases where you are providing a Vue Instance, you can emit an event, like "check-validation," on that instance for your descendant components to listen to. Subsequently, they can emit a validate Event with the validation Result back to the parent Component.

Here's a simple example to illustrate this: https://codepen.io/arossbach/pen/xxdxOVZ

            Vue.component('my-form', {
              provide () {
                return {
                  formBus: this.formBus,
                };
              },
              mounted() {
                setTimeout(() => {
                  this.formBus.$emit("check-validation");
                },4000);
                
                this.formBus.$on("validate-element", isValid => {     
                  this.isValidForm &&= isValid;
                });
              },
              data () {
                return {
                  formBus: new Vue(),
                  isValidForm: true,
                };
              },
              template: '<div><slot></slot></div>',
             
            });

            Vue.component('child', {
              inject: ['formBus'],
              template: '<div></div>',
              data() {
                return {
                 isValid: true,
                }
              },
              methods: {
                validate() {

                  this.isValid = Boolean(Math.round(Math.random()));
                  this.formBus.$emit("validate-element", this.isValid);
                }
              },
              created() {
                this.formBus.$on("check-validation", this.validate);
              }
            });

            new Vue({
              el: '#app',
              data () {
                return {
                };
              },
            });

HTML:

<div id="app">
  <my-form>
    <child></child>
    <child></child>
  </my-form>
</div>

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

I keep receiving a 400 (Bad Request) error when trying to delete with my REST API

I've successfully created an API and have managed to make POST and GET requests work flawlessly. However, I'm facing some trouble with the DELETE request. Every time I try to execute it, I encounter a 'DELETE http://localhost:3000/api 400 (B ...

What is the best way to set the focus on a Vue flat-pickr component?

Having trouble setting focus to the Vue flat-pickr component. Here's an example: <flat-pickr v-model="date_opened" id="file_opened" :config="flatpickr_config_date" :disabled="disableFileInfo&q ...

What is the best way to retrieve a state variable within the getServerSideProps() function in NextJS?

Introduction Greetings everyone, I am a newcomer to NextJS. Currently, I am in the process of developing a weather application that utilizes external APIs. My main task involves fetching data from an API and displaying it on the frontend. Desired Function ...

The issue of uploading files using Ajax in CodeIgniter and Jquery is causing problems

I am attempting to implement a file upload using Ajax in CodeIgniter, but it seems like my Jquery code is not properly retrieving the data from the form even though the file appears to be included in the POST message. Below is my controller: public funct ...

Tips for creating immersive 3D games on the web

I am fairly new to the world of HTML and Javascript, but I am diving into the Udacity interactive 3D course and experimenting with three.js + WebGL. I have managed to create and somewhat understand this: So far. (I am struggling to comprehend the API ...

Issues with rendering HTML5 drag and drop styles are not visible on a Windows Server 2003 platform

I am currently developing a file upload tool utilizing Valum's Ajax-Uploader as the foundation. The concept is reminiscent of how attaching files works in Gmail. Users should be able to simply drag and drop a file from their desktop into the browser w ...

Autocomplete feature seems to be functioning properly in the online demonstration, while it does not seem

I can see that the autocomplete feature is working in the example provided, but it's not functioning properly in my attempt. What could be causing this issue? <!doctype html> <html lang="en"> <head> <meta charset="utf-8> & ...

Adjusting the z-axis rotation in a three.js animated scene

Is there a way to add a function that changes the Z rotation value of the teapot from within the updateTeapot function? I came across this helpful answer on Three.js camera tilt up or down and keep horizon level. However, I am unsure how to integrate a z ...

What is the process for displaying an image based on a selection from a dropdown menu?

I am attempting to create a form that will show a movie poster once a user selects which movie they want to view. I have written a function for this purpose, but as a beginner in javascript, something seems to be going wrong. Any assistance you can provid ...

Encountering an Error in Laravel 8: Form Submission Issue - Uncaught TypeError Preventing Property Read

<a href="{{ url('/home') }}">Home</a> <a href="{{ route('logout') }}" onclick="event.preventDefault();document.getElementById('logout-form').submit();">Logout</a> <form ...

"Extracting key-value pairs from an observable in Angular 2: A step-by-step

Trying to display the key/value pairs from the server in Angular using RxJS. Below is the code snippet: let listener = c.listenFor('addMessage'); listener.subscribe(mesg => { console.log(mesg); }); However, it currently o ...

Using Angular components to manipulate the CSS in the DOM

Struggling with dom manipulation in an angular/node.js environment using typescript for my visualcomponent.html The second inline styling works fine, showing the h1 in blue color. However, I run into issues when trying to embed strings within the innerHTM ...

Error: Firebase is not recognized as a valid function

I have been attempting to go through the firebase Node tutorial at this URL: Running my node.js app leads to a crash with a "TypeError: Firebase is not a function" error. Here is an excerpt from my index.js file: var Firebase = require("firebase"); var f ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

What specific files from the Kendo core are required for utilizing Mobile and Angular functionalities?

After browsing through similar questions, I couldn't find a solution. Currently, I am experimenting with Kendo (open source core for now) in a Visual Studio Cordova project. Initially, disregarding Cordova, I am focusing on setting up a basic view wit ...

The functionality of Angular 2's AsyncPipe seems to be limited when working with an Observable

Encountering an Error: EXCEPTION: Unable to find a support object '[object Object]' in [files | async in Images@1:9] Here's the relevant part of the code snippet: <img *ngFor="#file of files | async" [src]="file.path"> Shown is the ...

What is the most effective way to access a variable from a service in all HTML files of Angular 2/4 components?

In my angular 4 project, I have an alert service where all components can set alerts, but only specific components display them in unique locations. My question is: how can I access a variable from this service across all HTML files? The structure of my s ...

Troubleshooting: Stage element not being recognized by Angular and CreateJS

I'm currently working on an Angular view that inherits from an ng-view element. Within the view file, there is a canvas that is controlled by a specific controller. My goal is to bring up a stage that allows me to add elements onto the canvas. Howev ...

What is the best way to refresh a PHP function based on a JavaScript event?

I have a website where a div tag shows all the values from a SQL database using PHP. I want to reload this div tag with a JavaScript event, such as clicking on an HTML button. Is it possible to bring back all the values from the SQL database and display th ...

Implementation of OAuth 2 Authorization Code Grant

I currently have the following setup: Resource Server: A basic RESTful API coded in PHP (using Slim and Doctrine) Auth Server: My custom implementation of an OAuth 2 server in PHP (utilizing Slim and Doctrine) Public Client: A Single Page Application (S ...