Skip to content
Advertisement

Conditionally set v-model in Vue

I have a series of inputs that could be either checkboxes or radio buttons, depending on a value in the data of my vue component.

In particular, I have a Question component, and questions may accept only one answer or multiple answers. I have a selected_answers array in my data, and I was thinking I could have the checkboxes target it as their v-model, while the radio buttons could target selected_answers[0]. This way, I don’t have to copy-paste che input elements and just change their type and v-model.

So, my solution would look something like this:

<input
    :type="question.accepts_multiple answers ? 'checkbox' : 'radio'"
    :id="'ans-' + answer.id"
    :value="answer.id"
    v-model="question.accepts_multiple_answers ? selected_answers : selected_answers[0]"
/>

However, eslint complains about my code:

'v-model' directives require the attribute value which is valid as LHS

What’s a way I can accomplish what I’m trying to do?

Advertisement

Answer

Ended up figuring it out by myself.

<input
    :type="question.accepts_multiple_answers ? 'checkbox' : 'radio'"
    :id="'ans-' + answer.id"
    :value="question.accepts_multiple_answers ? answer.id : [answer.id]"
    v-model="selected_answers"
/>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement