Best practices for utilizing switch statements with Vue data bindings

I have a straightforward scenario where I need a range input to update a button's text whenever the range value changes. My approach involves using Vue.js to bind data from an object that stores the range value and displays it on the button (and a counter for easier debugging).

In the provided example, when the range value is above 0, the text will show "Buy", otherwise it will display "Sell".

Play around with it here: http://jsfiddle.net/svwa79pe/1/

https://i.sstatic.net/F6FaQ.png https://i.sstatic.net/cWfuu.png

My goal now is to introduce a third button state based on whether the range value is positive, negative, or zero. While I can use Vue's ternary expression within handlebars / mustache syntax, I'm struggling to cover the third state. I'm looking for something akin to a switch statement in Vue, but haven't found anything like that in the documentation.

  • Is there a specific tool or method in Vue designed for this kind of logic that I might be overlooking?
  • Would it be more practical to create a custom method triggered by the range change event to achieve this functionality?
  • Could I be misusing the Vue template altogether? Are there alternative approaches using attributes or other techniques?

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
});

Answer №1

It is often recommended to avoid complex logic in the template. Instead, consider using a computed property when you need a value based on other data.

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

You can use simple if statements like above or switch statements as needed. In your template, you would use it like this:

<button>
  {{ buttonLabel }}
</button>

A complete example is provided below:

var statistics = {
  item : {
    price : 10,
    stock : 20,
    loot : 5,
    delta : 0
  }
}
var application = new Vue({
  el: '#application',
  data: statistics,
  computed:{
    buttonLabel(){
      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="application">
  <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>
      {{ buttonLabel }}
    </button>
  </span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there any practical use for keys in React outside of lists?

In my research, the emphasis was on using keys when rendering lists, such as this example: <ul> {array.map((item, index) => <li key={index}>{item}</li>)} </ul> Can keys be beneficial in contexts other than just lists? Are ...

What is the Dojo counterpart for jQuery's .live() function?

Is there a Dojo alternative to jQuery .live() function? http://api.jquery.com/live/ In my search, the only workaround I came across was to disconnect the event handlers in Dojo and then reconnect them when new dynamic content is added to the page. ...

What causes the error "Why is notify.js not being recognized as a function?"

Incorporating sources and links into my webpage, I included notify.js using the following code: <script src="/Scripts/jquery-3.5.1.js"></script> <script src="/Scripts/jquery-ui-1.12.1.js"></script> &l ...

What is the process for incorporating SQL into a JavaScript function?

I'm having trouble getting user input into my database. I have a functional block of SQL code that should insert the data, but I keep encountering "undefined" errors when running it. Here is the SQL code in question: <?php require 'creationli ...

Sustained database connectivity for seamless Ajax operations

I am currently working on an ajax call that retrieves data from a processing script called 'getajax.php'. The 'getajax.php' script contains all the necessary details such as database connection information, select queries, functions, e ...

Keep your eyes peeled for updates in jquery movements

Is there a way to detect changes in HTML content? I have a button that adds more HTML, but when I save the data using ajax, it doesn't capture the added HTML. Currently, when I click save, the new HTML is not recognized. $("#more_column").click(func ...

What is the best way to display a button only during office hours from 9am to 5pm using React.js or JavaScript?

If I want a button to only be visible from 9am to 5pm, how can this be achieved where the button is hidden outside of that time frame? ...

A guide on converting HTML and CSS to a PDF file using JavaScript

I'm facing a challenge where I need to create a custom quote in pdf using data retrieved in JavaScript and sent in HTML. However, the issue is that no library supports CSS for the PDF generation process. After some research, I came across HTML2CANVAS ...

The issue with Buefy table not properly passing props within the render function

Having trouble with the Buefy table component in a render function as the props are not being passed correctly. import { createElement as h } from '@vue/composition-api'; import { BTableColumn, BTable } from 'buefy/dist/esm/table'; h(B ...

Preventing Internet Explorer from automatically scrolling to the top of the page when a new HTML element is dynamically inserted using

On my webpage, I have an ASP:Grid with a small copy button in each row to copy the text inside that cell. The javascript function I created for copying the text is as follows: var copyText = function (textToCopy) { $(".copy").append("<textarea id=&ap ...

The issue with onclientclick in Asp.Net button

I am experiencing a peculiar problem that I cannot seem to solve. The issue revolves around a button that I have implemented using the following code: <asp:Button ID="btnSave" runat="server" ClientIDMode="Static" Text="Save" OnClientClick="return Confi ...

Steps for incorporating one item into another object

I'm struggling to add an object to another object. I've created an object with two properties and now I want to assign it to another object. $scope.urlMappings = {}; $scope.Mapping = function() { ...

Steps to successfully click a button once the popup window has finished loading entirely

Is there a way to programmatically click on an HTML element? I am currently using JQuery selectors to identify a button and then trigger a click event. $('span.firstBtn').click(); Once this button is clicked, a popup window appears. How can I w ...

What is the best way to connect to the Microsoft Azure Machine Learning Studio API - through Vue Axios or an Express

I am currently utilizing the following code to establish a connection with a web service. However, I now require assistance in connecting to the Microsoft Azure Machine Learning Studio Api using Vue Axios or Express. Can someone provide guidance? var http ...

Ways to transfer a variable from a Node.js script to a JavaScript file on the client side

Seeking guidance on how to transfer the "myBlogs" variable from my Node.js file ("server.js") to a frontend JavaScript file ("blogs.js"). I intend to utilize this variable in the JS file to iterate through the array it contains, generating a template for e ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Switching out one block of HTML with another in JavaScript is a powerful way to dynamically update

I am working on creating a feature on a webpage where clicking a button will change the HTML code inside a specific div. Essentially, I want to be able to update the content of a div by simply clicking a link. Here are two different sets of HTML code: Co ...

What is the best way to test a React component that includes a Router, Redux, and two Higher Order Components using Jest and Enzyme?

I'm currently facing a challenge with this issue. I have a React Component that is linked to React Router 4 and Redux store, and it's wrapped by two HOCs. It may sound complicated, but that's how it was implemented. Here's the export st ...

How come jQuery each is failing to iterate through all JSON items from two functions simultaneously with $.when?

After checking with the Chrome Network inspector, it appears that the json returns from both ajax functions are downloading completely. However, there seems to be an issue with the jQuery each function as it is only going through the first three items of t ...

How can I resolve the "AngularJS 1.6.6 component controller not registered" error plaguing my application?

I am currently using AngularJS version 1.6.6 along with Gulp for my project. Here are the snippets of my code, particularly focusing on the AppLayout component: /// app-layout.component.js angular.module('app').component('appLayout&ap ...