Reorder the cases and returns in Vue/Javascript for improved functionality

I have a table that displays Exam Results. The status of the results can be either Active or Nonactive, and further categorized into 4 conditions: Remind, Reminded, Correction, and Corrected. I've written a method using if else statements to change the button color and text based on the status, correctness, and reminder values:

methods: {
    // getColorBtn method
    // textButton method
    // getIcon method
    // getColorChip method
}

You can view the result here.

Below is an example data structure using Vue's data() method:

data() {
    return {
        // sample data for demonstration
    }
}

This is how the template looks like with Vue components:

<v-row>
    // Template code goes here
</v-row>

I'm looking to switch from using multiple if else statements to a Switch Case logic for better organization. I've made an attempt at it but struggling with the syntax. Here's what I've tried:

var buttonColor = ''
var buttonText = ''
var buttonIcon = ''
// Switch Case logic here

If you could provide guidance on how to make this work with multiple cases and results, it would be greatly appreciated. Thank you in advance for your help.

Answer №1

To organize your choices, utilize the new data function property to map them accordingly and then adjust the students array using a computed property. You can easily expand on the cases by updating the options array:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      isHide: true,
      /*icons: {
        mdiBellOutline,
        mdiBellCheckOutline,
      },*/
      students: [
        { no: '1', name: 'Ridho Mckinnon', status: 1, time: ' 08:04 - 09:58, 19/01/2021', isCorrect: 1, isRemind: 1,},
        { no: '2', name: 'Ridho Mckinnon', status: 1, time: ' 08:04 - 09:58, 19/01/2021', isCorrect: 0, isRemind: 1,},
        { no: '3', name: 'Ridho Mckinnon', status: 0, time: ' 08:04 - 09:58, 19/01/2021', isCorrect: 0, isRemind: 1,},
        { no: '4', name: 'Ridho Mckinnon', status: 0, time: ' 08:04 - 09:58, 19/01/2021', isCorrect: 0, isRemind: 0,},
      ],
      // 👇 new data property with mappings
      options: [
        {type: [1,1,1], color: 'v-btn--outlined theme--light primary--text', txt: 'Corrected', icon: 'd-none'},
        {type: [1,0,1], color: 'primary plain--text', txt: 'Correction', icon: 'd-none'},
        {type: [0,0,1], color: 'v-btn v-btn--text theme--light success--text shadow-none', txt: 'Reminded', icon: ''},
        {type: [0,0,0], color: 'v-btn v-btn--text theme--light primary--text shadow-none', txt: 'Remind', icon: ''}
      ]
    }
  },
  computed: {
    // 👇 computed property for adjusting your array
    getStudents() {
      const result = []
      this.students.forEach(s => {
        this.options.forEach(o => {
          if ([s.status, s.isCorrect, s.isRemind] == ''+o.type) {
            s.color = o.color
            s.txt = o.txt
            s.icon = o.icon
            result.push(s)
          }
        })
      })
      return result
    }
  },
  methods: {
    getColorChip(status) {
      return status === 1 ? 'v-chip-light-bg success--text' : 'v-chip-light-bg error--text'
    },
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfb9b0b1ab9fe9f1a7">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="205655455449465960120e58">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
                               <!-- 👇 loop with computed property -->
        <v-row v-for="student in getStudents" :key="student.no">
          <v-col xl="2" lg="2" md="2" sm="6" cols="12">
            <v-chip
            class="text-subtitle-2 text-md-caption text-lg-caption text-xl-caption"
            :color="getColorChip(student.status)"
            >
              {{ `${student.status ? 'Active': 'Nonactive'} ` }}
            </v-chip>
          </v-col>
          <v-col xl="3" lg="3" md="3" sm="6" cols="12">
            <div class="d-flex align-center">
              <div>
                <v-img src="../../../../assets/icons/calendar.svg" width="20"></v-img>
              </div>
              <span class="pl-2 text-subtitle-2">{{ student.time }}</span>
            </div>
          </v-col>
          <v-col xl="3" lg="3" md="3" sm="12" cols="12">
            <v-btn width="100%" :color="student.color">
              <v-icon v-show="isHide" class="mr-2" :class="student.icon">
                {{ student.icon }}
              </v-icon>
              {{ student.txt }}
            </v-btn>
          </v-col>
        </v-row>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4432312104766a3c">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9dfdcccddc0cfd0e99b87d1">[email protected]</a>/dist/vuetify.js"></script>

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

Reorganize the array or generate a new array using the indexes of the objects

I have a specific object that I need to render into table rows and cells using JSX... { "0": [ { "colIndex": 0, "data": { "richTextModule": "Data row 1 cell 1" } }, ...

Encountering issues importing Ace Document Object in a Vue webpack project?

In my Vue and Webpack project, I am trying to incorporate the Ace editor. My goal is to associate each file with a single instance of an Ace Document. To achieve this, I followed the default import method: import Ace from 'ace-builds' When atte ...

Identify when the user clicks on the URL bar or types in the browser's address bar using Jquery or JavaScript

In my current project, I'm faced with the challenge of interacting with the browser's URL bar. Specifically, I need to detect events using jQuery/JS when a user clicks on the address bar, types in it, or switches tabs. Is there a way to achieve t ...

Utilize the ng2-select component to incorporate multiple instances within a single webpage

Can someone help me figure out how to use two ng2-select components in my modal? I've checked out the documentation, but it doesn't provide any information on using more than one select. I'm not sure how to capture the selected values of ea ...

Matching objects in an array based on a specific property using the key of another object

To display information in the UI based on matching values between the data.examples array object's name.value property and the keys in the wcObject.notCoveredList, we need to create a logic. If there is a match, all corresponding values from wcObject ...

Distinguishing div identifiers for jQuery displaying and concealing

Although I am not a coder, I am still learning and trying to improve my skills. I have multiple div elements listed by a MySQL query. I require a JavaScript code that can display the class="qform" div based on which button is clicked. If button-1 is clic ...

What is the best way to send a Node.js variable to the inner part of a Pug script tag?

I am attempting to pass a variable from my Node.js backend to a Pug template and then use that variable inside a JavaScript script tag within the Pug file. Here's a snippet of my Node.js code: app.get('/profile', function (req, res) { var ...

Exploring the viability of utilizing microtime as a distinctive identifier

Is it feasible to use a user-submitted microtime value to track server session and encrypt data similar to an RSA passphrase? Would this method be reliable for generating auto/dynamic passphrases? Uncertain if this is the appropriate platform for discuss ...

Encountered an error: Unable to access property 'tween' of an undefined variable in the Masterslider.js script

My webpage features three sliders using Master Slider alongside Fullpage.js. var slider = new MasterSlider(); slider.setup('masterslider', { width: 300, height: 300, });   slider.control('lightbox'); slider.control('slidei ...

Is jQuery AJAX returning improperly formatted JSON when using the jsonp type?

$('#rn_s').keyup(function() { var rn = $('#rn_s').val(); if(rn.length == 9) { $.ajax({ url: 'http://routingnumbers.info/api/data.json?rn=' + rn, type: 'GET', dataT ...

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...

Eliminated the gap among the whitespace buttons within a bootstrap dialog

I am currently working on a web application using Bootstrap 3.3.7 and Bootstrap Confirmation 2.4.1. The confirmation function works effectively, but I have noticed that when the button (Delete) with the Confirmation is clicked, it results in some spacing i ...

Having trouble with .animate() function?

Struggling to animate the position of my background image $(function() { $('#nav1').bind('click',function(event){ $('ul.nav').stop().animate({backgroundPosition: 'right top'}, 1000); }); $(function() { ...

Navigate between tabs with a single click

Hey there! I'm having trouble putting together a webpage that features a sidebar. I want to make it so that clicking on one of the links at the top will switch the tab and its content accordingly. However, the current code I have isn't working an ...

Switching the audio file upon button click

I've been attempting to switch the audio file when a button is clicked but I keep encountering this error Uncaught TypeError: audio.load is not a function Below is my code, where the goal is to change the audio file upon pressing the button. If ...

jQuery functions correctly within jsfiddle, yet it encounters issues when utilized within WordPress

I've been experimenting with a jQuery script to grey out the screen. While it works perfectly on my jsFiddle link provided below, I'm having trouble getting it to work from within my WordPress plugin. Check out the working script on my jsFiddle ...

Submit function causes mutation in React form state

My current project involves learning React on my own and creating a small single-page React app using an Axios API. I'm facing a persistent issue with a POST request that keeps failing. After extensively using console.log, it appears that the form inp ...

Ways to prevent a specific class from using CSS styling

My HTML <body> <div id="finalparent"> <!--many parent divs here--> <div id="1stparent"> <div id="txt_blog_editor" class="box" style="width: 1097px;"> <div class="abc anotherclass"> </div> & ...

How can I locally store 3D models and textures using three.js?

Currently working on a game using three.js, where each game level is on a different page. However, when transitioning from one level to another, the browser reloads the page which can be quite slow. Is there a way to store 3D models locally so they don&apo ...

AngularJS encountered an error while attempting to create a module with obfuscated code, resulting in a $injector:

Attempting to obfuscate my angularjs application using mangling is resulting in an error. I have been advised to use ngmin to address this issue. Following this advice, I have successfully used ngmin to properly encapsulate my controller code within an arr ...