简体   繁体   中英

Confusion using v-bind:class ternary on a v-for element when referencing the properties of the v-for element

I believe I've hit a stumbling block in my understanding of Vue. As far as I know, it's valid to reference the property of an object that is being listed using a v-for. However, when I try to do this inside of a v-bind:class ternary operation, it fails for some reason.

Context:

What I'm trying to do is basically have a component inside a v-for element emit an event, which the v-for element will pick up, and adjust it's own properties based on. In this case, I'm determining whether or not an order is due as a boolean value set via a reference to the v-for element (ie element as elements).

Example:

I've simplified the below code slightly, but have tested it with these versions and the problem remains.

Html:

  <div class="order" :class="[order.due ? 'due' : '']" v-for="order in orders" v-cloak>
    <div class="name" v-cloak>ORDER #{{order.id}}</div>
    <time-count :date="order.submitted" v-on:due="due(order)"></time-count>
    <div class="status" v-cloak>
        {{order.status}}
    </div>
  </div>

and in JS, this method:

due(order) {
  order.due = true;
},

and in the component:

if (this.minute >= 15 || this.hour > 0 || this.day > 0) {
    this.$emit("due");
}

I have tested everything up to the point where I can see the order in the Vue object having the due property added, with the proper value associated with it (and the property doesn't exist before it's set). The ternary operator doesn't apply the class, even though I can see the the 'due' property being true for the specific order, like below:

{"order":"11","submitted":"2019-03-21 03:14:05","status":"CONFIRMED - AWAITING PAYMENT","due":true}

Vue cannot detect property addition or deletion . Try having an initial value (like false ) for due in the data section of your order component.

Properties that aren't available on the data object at the moment of the component creation are not reactive. You need to explicitly tell vue to add the new property.

Try this in your due method

due(order) {
 this.$set(this.order, 'due', true)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM