Andrejs Gubars
Andrejs Gubars

Reputation: 604

VueJS How to select only one item per row of 3 items inside a for loop?

I am a bit stuck with this. Problem is that I need to select (CLICK) only 1 item inside a list of items. So inside aaa > 1, 2, 3 I can select 1, 2 or 3 but not multiple. then inside bbb > 1, 2, 3 the same. But I cannot figure out because the end result should be aaa > 1 (selected), 2, 3 bbb > 1, 2(selected), 3 and etc... Here is a jsfiddle

https://jsfiddle.net/caliberdev/6c5xn8p9/

HTML:

 <div id="app">
  <ul>
    <li v-for="(item, key) in items">
      {{ item.value }}
      <ul>
        <li v-for="(v, i) in [1,2,3]" @click="activeItem(item.id, v)" :class="{active: ''}">{{ v }}</li>
      </ul>
    </li>
  </ul>
</div>

JS

new Vue({
  el: '#app',
  data: {
    items: [{
        id: 1,
        value: 'aaa'
      },
      {
        id: 2,
        value: 'bbb'
      },
      {
        id: 3,
        value: 'ccc'
      },
      {
        id: 4,
        value: 'ddd'
      },
      {
        id: 5,
        value: 'eee'
      },
      {
        id: 6,
        value: 'fff'
      },
      {
        id: 7,
        value: 'ggg'
      },
    ]
  },
  methods: {
    activateItem(top_id, bot_id) {
      console.log(top_id);
      console.log(bot_id);
    }
  }
})

CSS

.active {
  color: white;
  background: black;
}

Upvotes: 1

Views: 1175

Answers (2)

Guillaume
Guillaume

Reputation: 58

i suggest to set which one of you sub elements you want to be active directly inside your data items.

data: {
items:  items: [{
    id: 1,
    value: 'aaa',
    active: [1]
  },
  {
    id: 2,
    value: 'bbb',
    active: [2]
  },
  {
    id: 3,
    value: 'ccc',
    active: [1, 2]
  },
  {
    id: 4,
    value: 'ddd',
    active: []
  },
  {
    id: 5,
    value: 'eee',
    active: []
  },
  {
    id: 6,
    value: 'fff',
    active: []
  },
  {
    id: 7,
    value: 'ggg',
    active: []
  }
]

},

For more clearness here is the modified jsfiddle you provided: jsfiddle

hope i helped :)

All right i think un understand your question, i edited the jsfiddle, i kept the same logic but instead when you click on the list item you add or remove which one you want to set active (or unset active)

Upvotes: 0

Laziji
Laziji

Reputation: 93

Like this, don't know if it's what you want

<ul>
    <li v-for="item in items">
        {{ item.value }}
        <input v-for="i in [1,2,3]" :name="item.value" type="radio" :value="i" v-model="item.active">
    </li>
</ul>

Upvotes: 2

Related Questions