2

I'm currently building a "form kit" for vue, so I can use a single FormComponent for multiple different forms and configure the entire form with a configObject. This configObject could look something like that:

configObj = {
    name: 'SampleForm',
    classes: ['sample-form', 'and', 'more', 'classes']
    groups: [
        {
            name: 'email-address',
            classes: ['sample-class'],
            input: {
                type: 'text',
            },
            label: {
                value: 'E-Mail'
            },
            additionalHtml: [
                {
                    tag: 'button',                   //this should render a button: <button></button>
                    classes: ['additional', 'classes'],
                    value: 'OK',                      //the button text
                    events: {
                        click() { //the logic to execute on click }
                    }
                }
            ]
    ]

Based on that configObjet I want vue to render the individual forms, in that case:

<form id="SampleForm" class="sample-form and more classes">
    <div class="form-group email-address sample-class">
        <label>E-Mail:</label>
        <input type="text" />
        <button class="additional classes">Ok</button>
    </div>
</form>

The FormComponent imports the components for every formGroup, i.e. FormGroupText, FormGroupSelect, ... And the template for the FormGroupText component looks like that:

<template>
    <div class="form-group">
        <label>{{ config.label.value }}</label>
        <input :type="config.input.type" />
        <component v-for="element in config.additionalHtml" :key="element.tag" :is="element.tag"></component>

Now what's missing here are the events! And that's the question - can I dynamically add event listeners here?

I could just add

@click="element['click']

but then I had to add every possible event here. I want just the events specified in the configObject. I'm really not sure if this is possible.

Does someone has an idea how I could achieve this? Or also something similar, I simply don't want to code every single form I need - i want a reusable kit I can use to build forms.

Thanks in advance :)

1 Answer 1

2

Try binding $listeners with v-on="eventsObject"

In your case that would look like this:

<component
  v-for="element in config.additionalHtml"
  :key="element.tag"
  :is="element.tag"
  v-on="element.events"  // add this line
></component>

PS I would suggest changing the :key="element.tag" to something else. You can have more of the same tag in a loop, and then this will couse an error of duplicated key. Any way good luck 😉

Not the answer you're looking for? Browse other questions tagged or ask your own question.