Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to express switch statement with Vue data bindings

I have a simple use case for a range input that changes a button's text whenever the range's value changes. I'm using Vue.js to bind data from an object that is simply storing the range value, and spitting it back out to the button (and the counter, for easier debugging).

In the following fiddle, when the range value is greater than 0, the text reads "Buy", or else it reads "Sell".

Fiddle: http://jsfiddle.net/svwa79pe/1/

positive-state negative-state

What I want to do is show three button states depending on whether the range value is positive, negative, or zero. I can use Vue handlebar / mustache syntax to create a ternary expression, but I can't figure out how cover the third state. What I need is closer to a switch statement than ternary, but I can't seem to find an analog to that within Vue's documentation.

  • Does Vue contain a tool for this kind of logic that I don't know about?
  • Should I just handle this with a custom method that fires on the range change?
  • Am I just using the Vue template incorrectly? Is there a better way to do this with attributes or something?

HTML

<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>
      {{ (item.delta > 0) ? "Buy" : "Sell" }}
    </button>
  </span>
</div>

JS

var stats = {
    item : {
    price : 10,
    stock : 20,
    loot : 5,
    delta : 0
  }
}
var app = new Vue({
        el: '#app',
        data: stats
});
like image 512
Dpeif Avatar asked Sep 11 '25 22:09

Dpeif


1 Answers

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>
like image 95
Bert Avatar answered Sep 14 '25 12:09

Bert