1

I created a vuejs web component with VueCli3, the final compiled component looks like this:

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

<my-lib></my-lib>

This web component simply creates a hidden input with some value. when I inspect it in the browser:

<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>

I want to use this inside a form in a none-vue page alongside with other inputs, like this:

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

Now the problem is when I submit the form, only title parameter appears in the backend, the my_input param does not exist!

What should I do to make it work?

1 Answer 1

1

When you use web component with shadow DOM, the input elements within shadow DOM are not submitted with traditional form submission. Read here for more details.

In general, the only option is to introduce some JavaScript to submit your forms. The simple one I can think of is using FormData when the submit event is triggered and then manually introspecting all the 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");

    // Some way to access the custom form field's value
    formData.append("custom-field-name", customField.customValue);

    // Submit now
    // Write code to submit form using XHR or Fetch API
}

To save some keystrokes you can avoid the for loop as you can create FormData using existing form:

const form = document.querySelector("form");
const formData = new FormData(form);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer :) Do I have to send data via Ajax ?
@AhmadMobaraki, Use XHR or Fetch API!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.