Using a Vuejs web component as an input element in a non-Vue web application: A step-by-step guide

After creating a web component with VueJs using VueCli3, the compiled output appears as follows:

<script src="https://unpkg.com/vue"></script>
<script src="./my-lib.js"></script>

<my-lib></my-lib>

This particular web component generates a hidden input with a specific value. When inspected in the browser, it shows:

<my-lib>
    #shadow-root (open)
        <style type="text/css">....</style>
        <div data-v-1ca2f958="" id="app">
           <input type="hidden" name="my_input" value="some value">
        </div>
</my-lib>

The intention is to integrate this web component within a form on a non-Vue page along with other inputs, like so:

<form method="post" action="/test.php">
   <input type="text" name="title" value="foo">
   <my-lib></my-lib>
   <button type="submit">submit</button>
</form>

The issue arises when submitting the form, as only the 'title' parameter is received at the backend while the 'my_input' parameter does not come through. What steps should be taken to rectify this?

Answer №1

Utilizing web components with shadow DOM results in the input elements within shadow DOM not being included in traditional form submissions. For more information, check out this resource.

Typically, you will need to incorporate some JavaScript to handle form submissions. One straightforward approach is using FormData when the submit event occurs and then manually examining all custom elements.

function onSubmit() {


    const form = document.querySelector("form");

    const formData = new FormData();

    for (let x of form.elements) {
        formData.append(x.name,  x.value);
    }

    const customField = form.querySelector("my-lib");

    // Accessing the value of the custom form field
    formData.append("custom-field-name", customField.customValue);

    // Proceed with submission
    // Include code to submit the form using XHR or Fetch API
}

To simplify your workflow, you can skip the for loop by generating FormData from an existing form:

const form = document.querySelector("form");
const formData = new FormData(form);

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

Tips for effectively dividing React application components

Jumping into React to build an application seemed like a good idea at first, but now I realize the complexity of it. Let me walk you through my plan and see if it aligns with best practices: The goal is to develop a React App for organizing the subjects I ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

Issue with GMap Compatibility on Specific Web Browsers

I'm currently facing an issue with implementing gMap [1] on a website. The map is functioning properly in Chrome and Safari, but it fails to display in Firefox, IE, and Opera (latest versions of all). I have ensured that the Google Map API key loads a ...

Exploring the capabilities of utilizing filters within a ternary operator in AngularJS

Can a filter be applied to a variable in the template within a ternary operation? <img ng-src="{{ image_url && image_url|filter:"foo" || other_url }}"> In this scenario, the filter is custom-made and I prefer not to alter it to accommodate ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Unable to target a dynamic div and utilize solely its image

Can someone provide some assistance with a jQuery issue I am facing? I have a lengthy list of images directly uploaded from YouTube, each image has the same "v-code" as its corresponding video. To simplify the downloading process for all videos on one page ...

Tips for resolving the UNABLE_TO_GET_ISSUER_CERT_LOCALLY issue while attempting to install Sentry using npm or curl

https://i.stack.imgur.com/G8hfZ.png curl -sL -k https://sentry.io/get-cli/ | bash Even though I've specified not to verify the certificate with -k, I'm still facing issues trying to install it. The script is supposed to automatically install sen ...

Retrieving data from JSON in JavaScript

Extracting data from a JSON file and using a JavaScript script to visualize it through a graph. JSON file link: The JavaScript code responsible for drawing the graph is as follows: $(document).ready(function(){ google.charts.load('current', ...

I updated the script to include a feature that automatically adds a leading zero to hours, minutes, and seconds if they are less than 10. However, for some reason, the output still doesn't show the leading zero

I have successfully created a countdown timer that works effectively. One of the conditions I added is to display leading zeros for hours, minutes, and seconds if they are less than 10. The desired format is like this (06 : 08 : 09) instead of (6 : 8 : 9 ...

Using latitude and longitude coordinates to calculate the xyz position on earth in a three-dimensional environment (three

Exploring the wonders of three.js I am currently working on rendering objects at specific geocoordinates on a large sphere. I am close to finding a solution, but I am struggling to determine the correct xyz position from latitude and longitude. I have cr ...

Using Rails AJAX to dynamically load partials without the need to submit

Imagine creating a dynamic page layout with two interactive columns: | Design Your Pizza Form | Suggested Pizzas | As you customize your pizza using the form in the left column, the right column will start suggesting various types of pizzas based on your ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

Customize Material UI (MUI) Autocomplete with preset initial selections

My goal is to develop a unique MUI Autocomplete feature that showcases a series of numbers from 1 to 50. Upon user selection, the component should initially only show numbers 1, 6, 10, 12, and 24. If the user inputs '1', it should then display al ...

transform pixel coordinates to latitude and longitude dimensions

Seeking clarification on how the geo referencing process functions for images. Is there a method to accurately extract latitude and longitude information from this specific line of code? imageBounds = [map.unproject([0, 0], 20), map.unproject([1716,1178], ...

How to request permissions from a bot user in Discord.js version 14?

I need to verify my bot's permissions before it carries out a command. Previously, everything was functioning perfectly with this code: // Discord.js v13 if (interaction.guild.me.permissions.has(Permissions.FLAGS.MANAGE_MESSAGES)) { interaction.re ...

Trigger a re-render of VueTable2 within the child component

My current setup involves a customer component that contains a child component with a vuetable 2. I am in need of a way to refresh the table whenever a new customer is created or updated in the parent component. I was considering using $emit on the parent ...

Error encountered in onclick handler due to unterminated string literal in PHP and jQuery

Trying to utilize PHP to send variables into the onclick of an element is resulting in an "Unterminated string literal" error due to long strings. Below is a snippet of my PHP code: $query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

Running a Node Fetch POST call with a GraphQL query

I'm currently facing an issue while attempting to execute a POST request using a GraphQL query. The error message Must provide query string keeps appearing, even though the same request is functioning correctly in PostMan. This is how I have configur ...