Home > Software design >  how to add multiple bind multiple classes to element with multiple booleans using v-bind:class
how to add multiple bind multiple classes to element with multiple booleans using v-bind:class

Time:11-06

I am trying to assign classes into an element depending on whether or not a boolean is true. I was able to do this using v-bind:class for some classes. However now I want to do this again for another boolean at the same time. This is for a to-do list app.

my current code:

<div
  v-bind:
  v-bind:
  
  v-for="task in tasks"
>
  <!-- task for loop -->
</div>
data() {
  return {
    note_text: ' ',
    tasks: [
      {
        text: 'hello',
        checked: false,
        selected: true
      },
      {
        text: 'world',
        checked: false,
        selected: false
      }
    ]
  };
},

I tried doing :

<div
  v-bind:
  v-bind:
  
  v-for="task in tasks"
>
  <!-- task for loop -->
</div>

this didn't work because you cant have multiple v-bind:class

I also tried :

<div
  v-bind:
  v-for="task in tasks"
>
  <!-- task for loop -->
</div>

that didn't work but I forget what is said for why. I'm sorry if my code has weird please let me know how I can fix that I'm new to stackoverflow and any help is appreciated.

CodePudding user response:

Vue documentation has an example of binding classes using multiple data properties. Yours can be written like this:

<div
  :
  v-for="task in tasks"
>

CodePudding user response:

To achieve this requirement, You can pass an object to v-bind:class directive to dynamically toggle the classes.

Live Demo :

new Vue({
  el: '#app',
  data() {
    return {
      tasks: [
        {
          text: 'hello',
          checked: true,
          selected: true
        },
        {
          text: 'world',
          checked: false,
          selected: true
        }
      ]
    };
  }
})
.text-gray-600 {
 color: gray;
}
.line-through {
  text-decoration: line-through; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div
       v-for="(task, index) in tasks"
       :key="index"
       :
       >
    {{ task.text }}
  </div>
</div>

  • Related