What are some alternatives to using Switch Statements in VueJS filter component?

Recently, I developed a Vue Component that incorporates a simple filter feature using BootstrapVue.

My query pertains to JavaScript Switch Statements - it is common knowledge that they may not always be the most optimal choice due to potential debugging challenges and nested errors. Can anyone suggest an alternative approach that might be more efficient in handling scenarios like the one illustrated below?

 computed: {
    products() {
      switch (this.selectedFilter) {
        case "all": {
          let products = [];
          let min = 0;
          for (let i = 0; i < productItems.length - 1; i++) {
            min = i;
            for (let j = i + 1; j < productItems.length; j++) {
              if (productItems[j].order < productItems[min].order) {
                min = j;
              }
            }
            let temp = productItems[min];
            productItems[min] = productItems[i];
            productItems[i] = temp;
          }
          productItems.forEach(product => {
            products.push(product);
          });
          return products;
        }
        case "subscriptions": {
          let products = [];
          productItems.forEach(product => {
            if (product.type == "recurring") {
              products.push(product);
            }
          });
          return products;
        }
        case "onetime": {
          let products = [];
          productItems.forEach(product => {
            if (product.type == "onetime") {
              products.push(product);
            }
          });
          return products;
        }
        case "purchased": {
          let products = [];
          productItems.forEach(product => {
            if (product.purchased) {
              products.push(product);
            }
          });
          return products;
        }
        case "unpurchased": {
          let products = [];
          productItems.forEach(product => {
            if (!product.purchased) {
              products.push(product);
            }
          });
          return products;
        }
        default:
          return "Product";
      }
    }
  },
  data() {...}

Answer №1

Utilizing switch statements in the scenario you've illustrated is commendable, there's no issue with that aspect. However, optimizing the transformation of results into a more user-friendly format could enhance the functionality.

Implementing Array.prototype.sort() and Array.prototype.filter() would prove to be highly advantageous:

switch (this.selectedFilter) {
  case "all":
    return productItems.slice().sort((a, b) => a.order - b.order);
  case "subscriptions":
    return productItems.filter(product => product.type === "recurring");
  case "onetime":
    return productItems.filter(product => product.type === "onetime");
  case "purchased":
    return productItems.filter(product => product.purchased);
  case "unpurchased":
    return productItems.filter(product => !product.purchased);
  default:
    return [];
}

Additionally, it is advisable to consistently return a specific data type from your function, such as an array in this context, hence the modified default case. If displaying a placeholder when no items are present is necessary, handling that within your template declaration would be more appropriate.

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

Encountered an npm installation error in the console, with a post-installation error message indicating code

I implemented the postinstall command in my Node project with React, but I encountered numerous errors during the installation process in React. npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dbdcc9cac4cde ...

Is there a way to showcase the information contained within a JSON array on an HTML webpage?

Looking to incorporate the data from a Json array retrieved from an API into my HTML. What steps should I take to achieve this? Below is the Json array in question: { page: 2, per_page: 3, total: 12, total_pages: 4, data: [ { id: 4, ...

Is the button inactive until an action is taken?

In my coding project, I am working with two buttons. I am trying to figure out a way to disable the second button until the first button is clicked. Does anyone have any suggestions on how to achieve this using a combination of JavaScript and CSS? ...

AngularJS IP Address masking

Looking for an IP address mask plugin that works with AngularJS. I attempted to use the "Jquery Input IP Address Control" plugin, but it wasn't functioning properly. The problem I encountered was that the "ngModel" attribute wasn't capturing the ...

Managing Uploaded Files using Laravel and Vue.js

Currently, I am in the process of developing a Vue.js + Vuetify + Axios + Laravel framework for creating a dashboard. One of the functionalities I am working on is the user profile, which includes the ability for users to upload a profile picture and their ...

The dimensions of the sprites within Three.js geometry

I am interested in creating an animation of sprites moving along a figure, particularly sprites that walk along the figure. An example of what I envision can be seen here: http://armsglobe.chromeexperiments.com/ I found some helpful information related t ...

Switch focus between two text fields

Within my react application, I have a total of 10 material-UI textfields. The initial 8 textfields are contained within an expansion panel, while the remaining two textfields are housed in another expansion panel. I am seeking to set up a system where auto ...

What is the best way to serve my HTML and CSS files using my NODEJS server?

I have set up a nodejs server with the following code. Currently, I haven't included any references to HTML or CSS in the code because I am unsure how to do that. const http = require('http'); // Create an instance of the http server to ...

How to properly utilize $.ajaxComplete and $.ajaxError functions?

I have been utilizing the code snippet below for my ajax form submissions: $.ajax({ url: "", data: ilmoittautumisdata, type: "POST", success:function(){ }); error:function(){ }); }); However, I recall being advised to discontinue using success and erro ...

concentrate on the input box

Once I click on the CPM, my goal is to automatically place the cursor in the centralized field of this page: . Despite my attempts to use different code snippets in the console, I have not been successful. I experimented with document.getElementById("se ...

Limit the API call to only respond to requests from the localhost

I'm currently working on a website that uses API calls within the same node project. I would like to restrict most of these API calls to only be accessible by the localhost website. Is there a way to achieve this without implementing OAuth and simply ...

My code in NodeJS is not executing in the expected order due to its asynchronous nature

handleRegistration: function (user, req, res, next) { console.log('handleRegistration activated'); user.getData(function(err, info) { if (err) { console.log(err.toString, "error message"); return next(err); } e ...

What is the best way to trigger the second function on a click event?

Is there a way to trigger my 20 second timer with the click of a button, followed by an alert after the timer ends? HTML <aside class="start-box"> <button type="submit" class="btn btn-primary btn-lg" id="toggleBtn" onclick="startCloc ...

Sharing information between node servers and Nuxt/Vue clients using wildcard subdomains

We are currently developing a multi-tenant solution utilizing NodeJS/Express on the back end and VueJS/Nuxt on the front end. Each tenant will be assigned their own unique subdomain such as x.mysite.com, y.mysite.com, and so on. Our main concern is how to ...

Toggle Jquery menu with a click of a button

I need help with creating a menu for a forum that opens on click and closes on click. Here is the code I have so far: /*Custom BBPress admin links menu*/ function wpmudev_bbp_admin_links_in_menu($retval, $r, $args) { if ( is_user_logged_in() ) { $me ...

Troubleshooting minified JavaScript in live environment

Trying to wrap my head around AngularJS and Grunt. In my GruntFile.js, I have set up two grunt tasks for development and production. In production, I am using uglification to combine multiple js files into one. I am in need of some advice or tips on how t ...

Ways to enhance the appearance of the parent element when the radio button is clicked

Hey there! So, I have a situation where I'm working with two radio buttons and I want to apply certain CSS styles to the parent box (<div>) when a radio button is selected (checked). Here's how I want it to look: box-shadow: 0 0 5px #5cd05 ...

Incorporating an additional table dynamically based on height considerations – can you provide visuals as guidance?

The visual representation of my question far surpasses my verbal explanation. My intention is to insert a new table once the height of the previous table exceeds a specific HEIGHT limit, not a certain number of rows. This project does not involve creat ...

What is the correct method for adding a button to a popup in Leaflet Draw?

I need a button within a popup that can perform an action on the attached layer. L.marker(coors[i], { icon }) .addTo(this.drawnItem) .bindPopup(this._getCustomIcon(mix)) .openPopup(); Here is my _getCustomIcon() function: ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...