Proper way to express switch statement with Vue data bindings Proper way to express switch statement with Vue data bindings vue.js vue.js

Proper way to express switch statement with Vue data bindings


Typically you want to remove complex logic from the template. In this case you want a value based on some other data so this is an ideal use case for a computed property.

computed:{  btnText(){    if (this.item.delta > 0) return "Buy"    if (this.item.delta < 0) return "Sell"    return "Nothing"  }}

Here I'm just using simple if statements, but if you wanted to use a switch you certainly could. Used in your template like this:

<button>  {{ btnText }}</button>

Here is a working example.

var stats = {  item : {    price : 10,    stock : 20,    loot : 5,    delta : 0  }}var app = new Vue({  el: '#app',  data: stats,  computed:{    btnText(){      if (this.item.delta > 0) return "Buy"      if (this.item.delta < 0) return "Sell"      return "Nothing"    }  }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script><div id="app">  <span>    <button disabled="true">{{ item.delta }}</button>  </span>  <input type="range" v-model="item.delta" value="0" v-bind:max="item.stock" v-bind:min="0 - item.loot">  <span class="exchange">    <button>      {{ btnText }}    </button>  </span></div>