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

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...

Vite, Vue, and Vuetify: A multitude of inexplicable network requests happening

Excited to share that I've started working on my very first Vue project - a Simple CRUD Application. Utilizing Vite, Vue3, and Vuetify, with PNPM as the Package Manager. Development has been smooth so far, without encountering any major issues. Howev ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

Vue Components for managing relationships between parents and children

Is there a way to retrieve all Parent-Child relationships of Vue Components within a project? Whether through the command line or using console.log. Expected result: ├── rootpage │ ├── componentA │ │ ├── componentD │ ...

I'm experiencing an issue where a function call within a Vue.js v-for directive causes the loop to continue indefinitely, but I'm unsure of the cause

Here is the template I am working with: <template> <div> <div v-for="report in reports"> <div class="map" v-bind:id="mapID = report.started.toUpperCase()" v-text="report.started"> {{hello(mapID)}} </div& ...

Tips for displaying Jinja2 objects from Flask in a draggable list using Vue.js's v-for directive

Here's my Vue code: <div class="drag"> <h2>List 1 Draggable</h2> <draggable id="cat1" v-model="list" :move="checkMove" class="dragArea" :options="{group:'people'}"> <div v-for="element ...

Unlock the power of viewing numerous inputs simultaneously

Seeking guidance on how to allow users to preview images before uploading them. Currently, my code successfully previews images for one input field, but I am facing challenges when trying to add multiple pairs of inputs and images. How can I implement mul ...

Specify the location of the resize button (corner)

Scenario : At the bottom of the page, there is a resizable textarea, However, having the resize button at the bottom-right corner does not provide the best user experience (try it out), Issue : I am wondering if there is a way to move the resize butt ...

Ensure that you decode the URL before making any changes to the location in a

Hi everyone, I'm facing an issue and need your help. Let's say we have a URL like site.com/post?comments=1,2,3,4. When I paste it into the browser address bar, my app opens and decodes the URL to site.com/post?comments=1%2C2%2C3%2C4. How can I re ...

Exploring innovative CSS/Javascript techniques for creating intricate drawings

When using browsers other than Internet Explorer, the <canvas> element allows for advanced drawing. However, in IE, drawing with <div> elements can be slow for anything more than basic tasks. Is there a way to do basic drawing in IE 5+ using o ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

Vue - Syntax error: Unexpected token, expecting "}."

I recently started working with Vue and have encountered a simple component issue. Sometimes, when I run npm run serve or save a file that is already being served, I receive the following error message: E:\Development\website\app>npm run ...

Troubleshooting V-model errors within VueJS components

Just dipping into VueJS and trying out a chat feature from a tutorial. I noticed the tutorial uses v-model in a component, but when I replicate it, the component doesn't display on the screen and the console throws a "text is not defined" error. Strug ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

Is there a way to nest arrays within arrays in JavaScript?

Array ( [0] => Array ( [contactId] => 5 [companyId] => 54 [personName] => Awais [contactNo] => 0321-1111111 [contactType] => Partner ) ) data[0].personName I ...

Is there a way to incorporate a text box in javascript that displays the retrieved reference count from the database?

I'm currently working on creating a functionality that retrieves rows with the same ID from a database and displays them in a text box. Below is the PHP code I've written for retrieving all the rows: PHP: <?php include_once('pConfig ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

Obtaining response object when encountering 401 error in AngularJS

I am currently working with Angular 1.6.4, Express 4.15.2, and express-session. My goal is to identify whether a user is unauthorized to access a specific route by checking for the existence of the req.session.user parameter. If the user is not authorized, ...

Collaborating on a Vue project that was set up using webpack

We are currently working on a VueJS project that was generated with WebPack. Unfortunately, the source file we have is incomplete, making it impossible for us to generate the complete web app using just the source files. Here is an example of a page withi ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...