Categories
Vue Answers

How to add switch statement with Vue.js templates?

Spread the love

Sometimes, we want to add switch statement with Vue.js templates.

In this article, we’ll look at how to add switch statement with Vue.js templates.

How to add switch statement with Vue.js templates?

To add switch statement with Vue.js templates, we should put the switch statement in a computed property.

For instance, we write

<template>
  <div>
    <button>
      {{ btnText }}
    </button>
  </div>
</template>

<script>
export default {
  //...
  computed: {
    btnText() {
      switch (this.item.delta) {
        default:
          return "Nothing";
        case 0:
          return "Buy";
        case 1:
          return "Sell";
      }
    },
  },
  //...
};
</script>

to add the btnText computed property that checks the this.item.delta value with a switch statement.

We return 'Nothing' by default, 'Buy' if this.item.delta is 0, or 'Sell' if this.item.delta is 1.

Then we render btnText in the button as its text.

Conclusion

To add switch statement with Vue.js templates, we should put the switch statement in a computed property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *