[Vuejs]-I want to make a radio-like checkbox in VueJs

0๐Ÿ‘

new Vue({
   el: '#div',
   data: function() {
     return {
       names: ["VueJs", "ReactJs", "Angular", "jQuery", "BackBoneJs"],
       selected: null
     };
   },
   methods: {
     handleSelection (item) {
      this.selected = item
     },
     checkSelection (item) {
      return item === this.selected
     }
   }
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="div">
   <div v-for="name in names">
     <input type="checkbox"
       @click="handleSelection(name)"
       :checked="checkSelection(name)" />
     <label v-bind:for="name">{{ name }}</label>
   </div>
 </div>

I think that you can better handle all of this without an array at all, look at the fiddle

https://jsfiddle.net/hqsw04m3/1/

This way you have direct access to the selected value, and you dont need to re-initialize your array every time

0๐Ÿ‘

I would do something like this.

 new Vue({
   el: '#div',
   data: function() {
     return {
       names: ["VueJs", "ReactJs", "Angular", "jQuery", "BackBoneJs"],
       selected: null
     };
   }
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
 <div id="div">
   <div v-for="name in names">
     <input type="checkbox"
       :id="name"
       @click="selected = name"
       :checked="selected === name" />
     <label v-bind:for="name">{{ name }}</label>
   </div>
 </div>

Leave a comment