[Vuejs]-Setting a value in v-if block

3👍

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.

0👍

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>

Leave a comment