ottz0
ottz0

Reputation: 2605

Setting a value in v-if block

How do I use v-if to do two things

  1. Show The message and 2) set message.hasSublocationOutage to true.

So if there is an outage show the message and set the flag to true message.hasSublocationOutage Or pass true to a method

      <div v-if="!subLocation.outageTag.length - 1">
         There is a problem
      </div>

Upvotes: 0

Views: 4448

Answers (2)

David L
David L

Reputation: 33833

There seems to be some inherent flaws in your design, but you can invoke a method that calculates whether or not to display and sets the message at the same time.

HTML

<div v-if="canShowAndCalculate()">
    There is a problem
</div>

JS

export default {
    methods: {
        canShowAndCalculate() {
            if (subLocation.outageTag.length - 1) return false;

            // else
            message.hasSublocationOutage = true
            return true
        }
    }
}

As Andrey mentioned, this is highly unadvisable. Having side effects in your conditional logic hides core logic. Rather, you should update a boolean condition when your data changes, not the other way around.

As a side note, you could use a computed property like V Sambor suggested for better performance, but that hides the "wrong" implementation even further since computed properties should always be cached and flowing out, whereas you could expect a method to do both, even though in this case it is inadvisable.

Upvotes: 3

V. Sambor
V. Sambor

Reputation: 13389

You can do a computed method for this is pretty much the same as @David L answer only that this will cache your display result until some related variables changes their values.

computed: {
  display() {
    if (this.subLocation.outageTag.length - 1) {
      return false;
    }

    this.message.hasSublocationOutage = true;
    return true;
  }
}

Then in Html you can do:

<div v-if="display()">
    There is a problem
</div>

Upvotes: 0

Related Questions