1

在 vuejs 2.6 应用程序中,我列出了左侧带有复选框的项目,因为必须选择 1 个元素,例如:

<tr v-for="nextPersonalHostelBookmark, index in hostelBookmarks" :key="nextPersonalHostelBookmark.id">

    <td >

        <input
            type="checkbox"
            class="custom-control-input"
            id="custom_selected_personal_hostel_bookmark_id"
            name="custom_selected_personal_hostel_bookmark_id"
            v-model="selected_personal_hostel_bookmark_id"
        >
        <label class="custom-control-label" for="custom_selected_personal_hostel_bookmark_id">XX</label>

但是如果选择了 1 个元素,那么其他元素也会被选中,这不是我需要的。如何保留所选元素的 selected_personal_hostel_bookmark_id var ID?

4

1 回答 1

2

您应该watcher在模型上使用 a 来删除数组中的第一项。像这样:

<div id="app">
  <input type="checkbox" name="vehicle1" value="Bike" v-model="items"> I have a bike<br>
  <input type="checkbox" name="vehicle2" value="Car" v-model="items"> I have a car<br>
  <input type="checkbox" name="vehicle3" value="Boat" v-model="items"> I have a boat<br>
</div>
new Vue({
  el: '#app',
  data: {
    items: ['Car']
  },
  watch: {
    items(newVal) {
      // Do nothing f the array is empty or already only has one value
      if (newVal.length <= 1) {
        return
      }

      // Otherwise, remove the first item in the array
      newVal.shift()
    }
  }
})

您也可以在此处使用 JSFiddle

于 2019-11-12T16:36:48.533 回答