2
votes

I have a series of components that represents different form field types. These are designed not to have any dependency on their parents so all their various attributes are passed in as individual props.

I'm trying to write a wrapper component for these fields that will handle some logic that is specific to my current implementation.

The idea is that I'll have a component called mws-field that will handle the additional logic and then output the required component based on its type prop.

However, this means mapping all the props from the parent component onto every child component. Currently my mws-field template looks like this:

<template>
    <form-field-select v-if="field && type == 'select'" 
        :label="label" 
        :classes="classes" 
        :placeholder="placeholder" 
        :tooltip="tooltip" 
        :domName="field.domName" 
        :required="field.required" 
        :value="field.value"
        :disabled="field.vm.disabled"
        :review="field.vm.review"
        :errors="field.errors"
        :options="options"
    ></form-field-select>

    <form-field-text v-else-if="field && type == 'text'" 
        :label="label" 
        :classes="classes" 
        :placeholder="placeholder" 
        :tooltip="tooltip" 
        :domName="field.domName" 
        :required="field.required" 
        :value="field.value"
        :disabled="field.vm.disabled"
        :review="field.vm.review"
        :errors="field.errors"
    ></form-field-text>

    ... etc

</template>

I've got more than a dozen of these components and in the majority of cases they share the same set of props.

I thought the answer was in the render() method but as I understand it, this would need the functional flag, which isn't supported in components.

Is there a less verbose, neater, more manageable way of doing this?

1
What about passing all of these in an object instead? You can simply put all these props into an object, and pass them into your component.Terry
also, as of 11 hours ago, the newest version of Vue supports dynamic type on input elements. jsfiddle.net/w2x5em9zthanksd
@thanksd, that's really good to know, cheers!rhoward

1 Answers

1
votes

You can give v-bind an object to specify the props you want to pass:

<template>
  <form-field-select v-if="field && type == 'select'" v-bind="inputProps"/>
  <form-field-text v-else-if="field && type == 'text'" v-bind="inputProps"/>
</template>

data() {
  return {
    inputProps: {
      label: this.label,
      classes: this.classes,
      placeholder: this.placeholder,
      tooltip: this.tooltip,
      domName: this.field.domName,
      required: this.field.required,
      value: this.field.value,
      disabled: this.field.vm.disabled,
      review: this.field.vm.review,
      errors: this.field.errors,
      options: this.options,
    }
  }
}

Here's the documentation on v-bind.