ahoi
4 months ago
1286
7
Vue

Set radio-button value by bool in array

Posted 4 months ago by ahoi

I'd like to solve the following problem:

I got a data structure like that:

{
  "options": [
    {
      "id": 1,
      "title": "Car",
      "value": true
    },
    {
      "id": 2,
      "title": "Bike",
      "value": false
    },
    {
      "id": 3,
      "title": "Bus",
      "value": false
    }
  ]
}

Now I'd like to show a radio button for each option:

<div v-for="(option,index) in options" :key="index">
    <input type="radio" :id="index" :value="true" :name="'option-selected'" v-model="option.value">
    <label :for="index">{{option.title}}</label>
</div>

Result

I can click every radio button and every option.value is set to true.

My goal

Allow only one radio button to be true. Select Car to be true, as it's set on initial data. Unfortunately I can not use a select or something like that, because the user should be able to edit the title of each option, even without selecting it.

Now my question:

I guess I could use a watcher to watch options and watch for a change in value and unset all other values. But is this the best option?

Example

Here's an example that shows the problem: https://codepen.io/spqrinc/pen/NZZbjZ

Please sign in or create an account to participate in this conversation.