[Vuejs]-Vue allow only one element in array be true

0👍

If i understood your requirements correctly you can still do it with radio buttons. You can specify the value to be used inside the selected variable, as described here: https://v2.vuejs.org/v2/guide/forms.html#Radio-1. This means that you can set up a watcher and then mutate the options list accordingly:

selected: function (newVal) {
    this.options.forEach(option => {
      if (option.id === newVal) option.value = true
      else option.value = false
    })
    console.log(this.options)
}

Here is a sandbox to see it in action:
https://codesandbox.io/s/heuristic-goldberg-lilsw

Update: Just saw that you want to use the </b-switch> from buefy. You can still do something similar by calling a function from the input event which then mutates the options list according to the just changed element. Something like this:

<div v-for="(option,index) in options" :key="index">
      <div class="box">
        <div class="field">
           <b-switch v-model="option.value" @input="(modelValue) => onSwitchChanged(modelValue, option.id)">
            {{ option.title }}
           </b-switch>
          <label :for="index">{{ option.title }}</label>
        </div>
    </div>
</div>

function onSwitchChanged(modelValue, id) {
    if (!modelValue) return
    this.options.forEach(option => {
      if (option.id === id) option.value = true
      else option.value = false
    })
}

-1👍

If you want that Only One will be selected then you have to use radio button. Checkbox has options to select all But One by One.

Without watch you can use methods. Pass index to the method.

<input 
   type="checkbox"
   :id="index" 
   :value="option.id" 
   @click="selectAnOption(index)"
>

Method:

methods: {
  selectAnOption(index) {
   this.options[index].value = true
  }
}

Full Code here: https://jsfiddle.net/8ktdp9ew/

Leave a comment