Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - Bind value of object to a checkbox value

I want to put the value of every item into array selectedParks. The problem is, the value is always set to string "item", and not the value of the actual item (it's a Park Object).

Code:

<ul class="list-group no-bullets">
    <li class="list-group-item" v-for="item in parks">
        <label><input type="checkbox" value="item" v-model="selectedParks"/> {{item.name}}</label>
    </li>
</ul>
<span>Checked: {{selectedParks}}</span>

I know that the actual item is bound correctly, because {{item.name}} shows the correct value.

Docs (multiple checkboxes bound to the same array): https://vuejs.org/v2/guide/forms.html

like image 436
Green_qaue Avatar asked Oct 26 '17 11:10

Green_qaue


People also ask

What is @input in Vue JS?

It provides two-way data binding by binding the input text element and the value binded to a variable assigned.

What is the difference between v-model and V-bind?

v-bind is a one-way binding. v-model is used for binding form elements like inputs, radio buttons, textarea, checkboxes. It is used for binding data, attributes, expressions, class, styles. V-model is input value sensitive.

Which Vue attribute is used to connect the value of a form element to a data property?

Value Bindings We can use v-bind to achieve that. In addition, using v-bind allows us to bind the input value to non-string values.

What is v-model lazy?

lazy. By default, v-model syncs with the state of the Vue instance (data properties) on every input event - which means every single time the value of our input changes. The . lazy modifier changes our v-model so it only syncs after change events. The change event is triggered when a change is commited.


1 Answers

That because value is being assessed as a string, you need to use v-bind to set it as an object:

<input type="checkbox" v-bind:value="item" v-model="selectedParks"/>

or the colon shorthand:

<input type="checkbox" :value="item" v-model="selectedParks"/>
like image 113
craig_h Avatar answered Nov 01 '22 16:11

craig_h