Home > other >  v-bind class not changing css on object properties
v-bind class not changing css on object properties

Time:10-24

I'm trying to dynamically change some css on some buttons based on object props in a list, here is my data im rendering out below, I'm trying to follow the docs and my setup seems fine but I must be missing something https://vuejs.org/v2/guide/class-and-style.html hoping someone can point it out :) many thanks

 invoices:[
        {id: 0, number: 123, amount:"$1,235", status:"open", isOpen:true, isUnpaid:false},
        {id: 1, number: 123, amount:"$1,235", status:"unpaid", isOpen:true, isUnpaid:false},
        {id: 2, number: 123, amount:"$1,235", status:"open", isOpen:true, isUnpaid:false},
      
      ],

here is my attempt to write the template and use vbind to toggle the classes depending on invoice.isOpen or invoice.isUnpaid

 <div id="invoicesDiv" v-for="invoice in invoices" :key="invoice.number">
                              
                               <img v-bind:style="{ 'margin-top':'.5em'}" src="../assets/svg/logo.svg" height="40px"/>
                                
                                <section>
                                  <small>Invoice No.</small>
                                  <p>{{invoice.number}}</p>
                                </section>

                                <section>
                                  <small>USD</small>
                                  <p>{{invoice.amount}}</p>
                                </section>

                                <section>
                                  <button v-bind:class="{open: invoice.isOpen, unpaid: invoice.isUnpaid}">{{invoice.status}}</button>
                                </section>

                                <img src="../assets/agency/ic_actions-1.svg" height="30px"/>
                            </div>

as you can see the section button is supposed to update classes to either -> open or unpaid but unfortunately it only seems to update to the open class :(

my CSS

.unpaid{
  background-color: red;
  border:none;
}
.open{
  background-color: green;
  border:none;
}

CodePudding user response:

  1. Binded classes must be on an Array
  2. The class name could be enclosed on single quotes
  3. Your conditions must return Boolean
<button :class="[{'open': invoice.isOpen}, {'unpaid': invoice.isUnpaid}]">
   {{invoice.status}}
</button>

CodePudding user response:

Enclose the class names in single quotes

<button v-bind:class="{'open': invoice.isOpen, 'unpaid': invoice.isUnpaid}">{{invoice.status}}</button>

and make sure the isOpen and isUnpaid hold the expected boolean values so that you could observe the difference on the UI

  • Related