The radio buttons' behavior is not as I expected when I am being lazy to use v-bind to dynamically bind the properties of the options to the template.
I am trying to dynamically render the options by an javascript object. However, it behaves differently when I am binding the properties differently. Even after checking the output HTML, I am not sure why the problem exists.
This is the Vue instance for backend data.
const app = new Vue({
el: '#app',
data: {
inputs: {
radioDynamic: '',
radioDynamicOptions: [
{
id: 'Light',
label: 'Blue',
value: 'Light',
},
{
id: 'Dark',
label: 'Red',
value: 'Dark',
},
],
},
},
template: `
<div>
<h4>Radios Dynamic Options</h4>
<!-- case 1: It works fine when I bind properties individually>
<template v-for="(option, index) in inputs.radioDynamicOptions">
<input v-model="inputs.radioDynamic" type="radio" :value="option.value" :id="option.value">
<label :for="option.value">{{ option.label }}</label>
<br v-if="index < inputs.radioDynamicOptions.length">
</template>
-->
<!-- case 2: the options are rendered as a single radio button which is not able to function correctly when I bind the object directly with v-bind="object".
<template v-for="(option, index) in inputs.radioDynamicOptions">
<input v-model="inputs.radioDynamic" type="radio" v-bind="option">
<label :for="option.value">{{ option.label }}</label>
<br v-if="index < inputs.radioDynamicOptions.length">
</template>
-->
<p><strong>Radios:</strong>{{ inputs.radioDynamic }}</p>
</div>
`,
})
<case 1 HTML output>
<h4>Radios Dynamic Options</h4>
<input type="radio" id="Light" value="Light">
<label for="Light">Blue</label>
<br>
<input type="radio" id="Dark" value="Dark">
<label for="Dark">Red</label>
<br>
<p><strong>Radios:</strong>Dark</p>
<case 2 HTML output>
<h4>Radios Dynamic Options</h4>
<input type="radio" id="Light" label="Blue" value="Light">
<label for="Light">Blue</label>
<br>
<input type="radio" id="Dark" label="Red" value="Dark">
<label for="Dark">Red</label>
<br>
<p><strong>Radios:</strong></p>
I expect the case 2 method, which is using v-bind="object", should generate the same result like v-bind:id="object.id" v-bind:value="object.value" But it turns out that I can't select the radio button individually and the selected value isn't pushed into the array.
This is my very first question here. Please forgive if my expression or format isn't good or qualified enough. Thanks and have a great day~