[Vuejs]-Vue.js how to render dynamic component?

0👍

If I do get your question clearly, I think what you need is v-for. See Vue3 Documentation: List Rendering

You don’t need to send the whole HTML text like option 1 from backend, given that is uncessary, and option 1 will be involved to either Element.appendChild() in javaScript or v-html in Vue template (not secure).

You can simply use option 2 data, assuming currently you only have name and label, which should be Objects inside an Array:

data = [
  zip_code: {
    name: 'zip_code',
    label: 'Zip code'
  },
  city: {
    name: 'city',
    label: 'City'
  }
]

Then use v-for within your template:

<template>
  <div>
    <base-input-component
      v-for="(item, index) in data"
      :key="index"
      :name="item.name"
      :label="item.label"
    />
  </div>
</template>

Equals to:

<template>
  <div>
    <base-input-component
      name="zip_code"
      label="Zip code"
    />
    <base-input-component
      name="city"
      label="City"
    />
  </div>
</template>

That should render all dynamic base-input-component you want.

Leave a comment