Home > other >  generate fields based on json data - how to solve on selection / checkboxes
generate fields based on json data - how to solve on selection / checkboxes

Time:10-01

I want to generate input fields in bootstrap-vue code based on a json file.

I loop over that array and my b-form-input fields work very well - problem is that I need also some selection fields b-form-select and checkboxes b-form-checkbox.

How can I solve that and how can I check in my template if there is any selection or checkboxes in my json?

Because I want to have multiple json files and these are all different..

Thank You!

<template>
  <div v-for="item in testJSON" :key="item">
    <label class="mt-2">{{item.label}}</label>
    <b-form-input :type="item.type" v-model="item.value"></b-form-input>
    <b-form-select :options="item.options"></b-form-select>
  </div>
</template>

my script:

<script>

import test from './json/test.json'

export default {
  name: 'Test',
  data() {
    return {
      testJSON: test,
    }
  }
}

</script> 

my imported json:

[
    {
        "number": "1111",
        "key": "key1",
        "label": "Input 1",
        "type": "text",
        "value": ""
    },

    {
        "number": "2222",
        "key": "key2",
        "label": "Input 2",
        "type": "text",
        "value": ""
    },

    {
        "number": "3333",
        "key": "key3",
        "label": "Input 3",
        "type": "number",
        "value": ""
    }
    {
        "number": "4444",
        "key": "key4",
        "label": "Select Input",
        "options": [
            { "text": "Value 1", "value": "value1" },
            { "text": "Value 2", "value": "value2" },
            { "text": "Value 3", "value": "value3" },
            { "text": "Value 4", "value": "value" }
          ],
        "value": ""
    }
]

CodePudding user response:

I would think that either

A: You need to have an options array (even if it is empty) in every object.

Or

B: You need to check in you template if the options exist like

<b-form-select v-if="item.options" :options="item.options"></b-form-select>

I guess a similar think with your checkboxes since you have not actually supplied any code for that.

  • Related