Vue2 dynamic v-model for a group

521 views Asked by At

I am working on a housing form and I am stuck somewhere and I am hoping someone give me a solution to my problem.

So, when you select in a form that your house have 2 floors, then you get to write each floor how many rooms, toilets, balcony etc has..

My issue is to "group" these answers somehow that I could send it to my backend and "read" those answers.

so this is what I did so far:

data() {
  return {
    flooroptions: [
      {
        name: 'Rooms',
        id: '1',
      },
      {
        name: 'Balcony',
        id: '2',
      },
      {
        name: 'Toilets',
        id: '3',
      },
    ],
    floors: '',
    floor1: [],
  },
}

and if I loop through like this:

<div class="" v-for="(opt, index) in flooroptions">
  <input type="number" name="" value="" v-model="floor1[index]">
</div>

I can see my data using floor1:

{{ floor1 }}

But if in the form someone selects that 1st floor has 2 rooms and does not add any other input than I get to floor1 only 2

How would be better approach for this type of problem ??

PS. Everyfloor will have this flooroptions loop and they can input number of each option for each floor, and I want to be able to read that number correctly..

1

There are 1 answers

2
Daniel On

if I understand correctly, I would...

data() {
  return {
    flooroptions: [
    {
      name: 'Rooms',
      id: '1',
    },
    {
      name: 'Balcony',
      id: '2',
    },
    {
      name: 'Toilets',
      id: '3',
    },
    ],
    numFloors: 2,
    floorData: [
      {'Rooms':0, 'Balcony':0, 'Toilets':2},
      {'Rooms':2, 'Balcony':1, 'Toilets':0}
    ],
  },
}

and loop through like this:

<div v-for="f in numFloors">
  <div class="" v-for="opt in flooroptions">
    <input type="number" name="" value="" v-model="floorData[f][opt.name]">
  </div>
</div>

or... if you want to pass less data and the id's are know on the backen

data() {
  return {
    flooroptions: {
      1: {
        name: 'Rooms'
      },
      2: {
        name: 'Balcony'
      },
      3: {
        name: 'Toilets'
      },
    },
    numFloors: 2,
    floorData: [
      {1:0, 2:0, 3:2},
      {1:2, 2:1, 3:0}
    ],
  },
}

and loop through like this:

<div v-for="f in numFloors">
  <div class="" v-for="(opt, i) in flooroptions">
    <input type="number" name="" value="" v-model="floorData[f][i]">
  </div>
</div>