[Vuejs]-Preselect radio input in Vue component in complex v-for loop

0👍

Thanks to the pointers from Daniel and Roy J, I was able to resolve this reasonably cleanly by adding a method to loop through the incoming fields and update the entries object accordingly.

   getForm() {
        const vm = this
        axios
            .post('/path/to/gf/api', {
                id: vm.formId,
            })
            .then(result => {
                vm.form = result.data
                vm.fields = result.data.fields
                vm.getRadios()
            })
            .catch(err => {
                console.log(err)
            })
    },
    getRadios() {
        let radios = this.fields.filter(field => field.type == 'radio')
        radios.forEach(radio => {
            let selected = radio.choices.find(
                choice => choice.isSelected == true
            )
            this.entries[`input_${radio.id}`] = selected.value
        })
    },

I also added

 :checked="choice.isSelected"

on the template, along with the v-model as before.

-1👍

If you’re not using entries for anything else, you don’t need it at all. You don’t need to v-model, you just want to set checked, which is pretty straightforward:

:checked="choice.isSelected"
new Vue({
  el: '#app',
  data: {
    fields: []
  },
  methods: {
    fetchData() {
      setTimeout(() => {
        this.fields = [
          {
            id: 1,
            type: 'radio',
            choices: [
              {
                isSelected: false,
                value: 1,
                text: 'one'
              },
              {
                isSelected: true,
                value: 2,
                text: 'two'
              }
            ]
          },
          {
            id: 2,
            type: 'radio',
            choices: [
              {
                isSelected: true,
                value: 1,
                text: 'three'
              },
              {
                isSelected: false,
                value: 2,
                text: 'four'
              }
            ]
          },
        ];
      }, 500);
    }
  },
  created() {
    this.fetchData();
  }
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<form id="app">
  <div v-for="field in fields" :key="field.id" :class="`field field__${field.type}`">
    <div v-for="(choice, index) in field.choices" :key="choice.value">
      <input type="radio" :id="`gf_${index}_${field.id}`" :name="`input_${field.id}`" :value="choice.value" :checked="choice.isSelected">
      <label :for="`gf_${index}_${field.id}`">{{ choice.text }}</label>
    </div>
  </div>
</form>

Leave a comment