I have a problem with VueJS when setting the value of an input radio AND v-model. I cant understand why I can not setting dynamically a value to an input and use a model to retrive what input the user selected.
In code is easier to understand:
export default {
props: ["question", "currentQuestion"],
data() {
return {
answer: undefined
}
},
computed: {
isCurrent() {
return this.currentQuestion && this.currentQuestion.id == this.question.id;
}
},
methods: {
groupName(question) {
return 'question_id_' + question.id
},
inputType(question) {
if (question.question_type_id == 2) return "checkbox";
return "radio";
}
},
mounted() {
console.log('Component mounted.')
}
}
<template>
<ul v-if="question.question_type_id != 4">
<li v-for="option in question.options" :key="option.id">
<div class="form-group">
<label>
<input v-model="answer" :value="option.id" :type="inputType(question)"
:name="groupName(question)" />
{{option.option}}
</label>
</div>
</li>
</ul>
</template>
So, in case there are 4 options, the user would see 4 radio buttons, each one with the "option.id" as a value and, WHEN the user clicks the radio button, the model "answer" would be populated with that value.
Now, when I try to compile this file, I get this error message:
- :value="option.id" conflicts with v-model on the same element because the latter already expands to a value binding internally
So, could anyone help me understand how do I dynamically set a value to an input AND asssociate a model to retrieve the value when the input is selected?
By the way, VueJS documentation at this page says exactly what I am trying to do: https://v2.vuejs.org/v2/guide/forms.html
Any help is very appreciated.
The main issue here is that you have a dynamic type on the input element, so I expect Vue is getting a little confused. value
is not valid in combination with v-model
for a checkbox input, unless you are binding to an array.
You can solve that by using a v-if/v-else.
<label>
<input v-if="question.question_type_id == 2"
v-model="answer"
type="checkbox"
:name="groupName(question)" />
<input v-else
v-model="answer"
:value="option.id"
type="radio"
:name="groupName(question)" />
{{option.option}}
</label>
Working example.
There are other issues, but this addresses the error you mention in the question. For one, it doesn't make much sense for more than one checkbox to be bound to a single v-model
, unless you are binding to an array. In that case, you would have to swap what type answer
is based on whether is a radio, a checkbox with a single value or a checkbox with multiple values. Seems like it would get complicated.
the proper way is to use placeholder.
<input :placeholder="option.id" v-model="answer" @input="functionToChangeValue($event)"/>
! DO NOT USE VALUE AND V-MODEL TOGETHER it is because v-model create two way biding and your code brake
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With