How to add a class in a label tag of a dynamically selected input by vue.js?

0

I'm using Boostrap and I have a sector in the form where the client will choose some items, and when clicking on the item the bootstrap adds the active class in the selected item, and with css I do the item to change color.

Getting more or less like this:

<label class="btn bg-grey active">
  <input type="checkbox" name="tagslist[]" value="valor"> Titulo
</label>

I'm using vue.js to create the items dynamically through data in json. And to select the checkboxes automatically according to the open registry.

But my problem is that in vue.js when it starts by checking the items I need, it only does the checkbox, but does not add the active class to the label, thus:

<label class="btn bg-grey">
  <input type="checkbox" name="tagslist[]" value="valor" checked> Titulo
</label>

How do I add this class to the parent tag of this checkbox input?

asked by anonymous 01.11.2018 / 02:40

1 answer

1

You can do this:

v-bind:class="{ active: seltags.includes(keyoption) }"

The code above:

  • Add the code to label

    <label class="btn bg-grey">
    
  • Checks whether the object seltags contains keyoption if already, returns true if not false

  • return will determine whether the active class will be added.

To solve the problem quoted via comment:

  

If you click on the square of the checkbox, it changes color showing this selected but does not checkbox.

just remove the attribute: data-toggle="buttons"

Example running

new Vue({
  el: '#v-for-tags',
  data: {
     seltags: ["feminino","masculino"],
     tagsitens: {"codes":{"feminino":{"tagtitulo":"Mulheres","tagslug":"women"},"infantil":{"tagtitulo":"Crianças","tagslug":"childs"},"masculino":{"tagtitulo":"Homens","tagslug":"men"}},"list": ["feminino","infantil","masculino"]}
  },
});
.btn.bg-grey.active {
    background-color: #673ab7 !important;
}

.iconsdinamic {
    float: left;
    margin-left: 10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script><scriptsrc="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script><divclass="btn-group-toggle" id="v-for-tags">
    <div v-for="(option, keyoption) in tagsitens.codes" class="iconsdinamic">
        <label class="btn bg-grey" v-bind:class="{ active: seltags.includes(keyoption) }">
          <input type="checkbox" name="tagslist[]" autocomplete="off" v-bind:value="keyoption" v-model="seltags"> {{ option.tagtitulo }}
        </label>
   </div>
</div>

Reference

01.11.2018 / 03:47