简体   繁体   中英

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;
}

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>

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM