javascriptvue.jsvuejs2vue-directives

can I bind to other input attribute besides value attribute in vuejs


I'm new to frontend javascript frameworks. Currently working on a piece of code and I'm curios if it's possible to bind some other input attribute than value to v-model in VueJS. Here's what I mean:

In my html I have input like so:

<input type="checkbox" name="labels[]" id="label_{{$label->id}}" value="{{$label->id}} v-model="checked">

And then later I want checked items to be shown by their names ($label->name) but I still need their values to be their ids for the backend.

<div v-for="label in checked" >@{{ label }}</div>

This of course returns id of the item but I need name. Is this possible?


Solution

  • You can use true-value and false-value:

    <input 
     type="checkbox" 
     name="labels[]" 
     id="label_{{$label->id}}" 
     value="{{$label->id}}" 
     v-model="checked"
     true-value="{{$label->name}}"
     false-value="something else" 
     <!-- quote is not required inside true-value, false-value. 
      it will automatically set the type -->
    >
    

    Excerpt from the doc:

    The true-value and false-value attributes don’t affect the input’s value attribute, because browsers don’t include unchecked boxes in form submissions.