[Vuejs]-Vue @click not changing class

0👍

An <input> element can’t have content.

So you’ve got this structure:

<input>{{ food }}</input>            

But that’s misleading as the <input> tag will be closed automatically. What you’ll end up with will actually be some text next to a checkbox, not inside it.

You probably want something similar to this:

<label :class="{marked: food === checked}" @click="checked = food">
  <input type="checkbox"> {{ food }}
</label>              

There are some other problems involving deselection and multiple selections. I’ve tried to fix those in the example below:

new Vue({
  el: '#app',
  
  data: {
    checked: [],

    list: [
      {
        id: 0,
        category: 'Bakery',
        food: ['bread','muffins','pie']
      },
      {
        id: 1,
        category: 'Fruits',
        food: ['apple','bananna','orange']
      },
      {
        id: 2,
        category: 'Diary',
        food: ['cheese','milk','yogurt']
      }
    ]
  }
})
.marked{
    text-decoration: line-through;
}
<script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>

<div id="app">
  <ul v-for="item in list">
    <li v-for="food in item.food" class="list-group-item">
      <label :class="{marked: checked.includes(food)}">
        <input type="checkbox" v-model="checked" :value="food">{{ food }}
      </label>
    </li>
  </ul>
</div>

Leave a comment