What is the best way to assign a class to multiple choices in Vue.js?

My Vue.js bound HTML includes the following:

<span :class="[obj.status === 'Online' ? 'badge-success' : obj.status === 'Updating' ? 'badge-warning' : 'badge-danger', 'badge badge-pill']">{{obj.status}}</span>

I am looking to introduce a new variant:

If obj.status === 'Updating', then I want the class to be badge-warning.

What is the most efficient way to achieve this? I believe adding another ternary within the existing one might make it look cluttered.

Answer №1

<span v-if="obj.status === 'Online'" class="badge-success">
   {{obj.status}}
</span>

<span v-if="obj.status === 'Updating'" class="badge-warning">
   {{obj.status}}
</span>

<span v-if="obj.status !== 'Updating' && obj.status !== 'Online'" class="badge-default">
    {{obj.status}}
</span>

Rendering content based on the status property is a great option.

Alternatively, you can utilize a switch-case statement to determine the class:

new Vue({
  el: "#app",
  data: {
    obj: {
       status: 'Online'
    }
  },
  methods: {
  getBadgeClass(status) {
      switch(status) {
          case 'Online':
               return 'badge-success';
          case 'Updating':
               return 'badge-warning';
          default:
               return 'badge-default'
      }
    }
  }
})

Then, in your template, you can apply this approach:

<span :class="getBadgeClass(obj.status)">{{obj.status}}</span>

Answer №2

If the Status is not online, you have the option to include another tertiary operator as demonstrated below:

 <span :class="[obj.status === 'Online' ? 'badge-success' : (obj.status === 'updating'?'badge-warning':'badge-danger'), 'badge badge-pill']">{{obj.status}}</span>

Answer №3

To streamline your class assignment, consider converting it into a method:

new Vue({
  el: "#app",
  data: {
    myValues: [
      {status: 'Online'},
      {status: 'Updating'}
    ]
  },
  methods: {
    assignedClasses(status) {
      var classToAssign; 
      if(status === 'Online'){
        classToAssign = 'badge-success';
      }
      else if(status === 'Updating') {
        classToAssign = 'badge-warning';
      }
      else {
        classToAssign = 'badge-danger';
      }
      
      return classToAssign;
    }
  }
})
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c1e1313080f080e1d0c3c48524d524d">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(obj, index) in myValues" :key="index">
    <span class="badge badge-pill" :class="assignedClasses(obj.status)">{{obj.status}}</span>
  </div> 
</div>

Answer №4

Here is an example of how you can implement multiple conditions:

<span 
:class="[{'highlight-green':data.mode === 'active', 'highlight-yellow':data.mode === 'inactive', 'highlight-red':data.mode === 'error'}, 'mode-indicator']"
>
{{data.mode}}
</span>

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

Achieving Vertical Alignment of Content in Bootstrap 5

I've experimented with different approaches based on search results, StackOverflow suggestions, and examining existing code snippets. Here is the snippet of code I am working with: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a ...

What is the best way to showcase elements from an array of strings in the app only if they have a length greater than zero?

I'm currently developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). This application showcases a list of movie cards. Within the MoviesList component (src\components\MoviesList.vue), the followi ...

JavaScript: an array of objects contained within another array of objects

Here is an example dataset for reference: var info = [ {row: 0, col: 0, value: [{x: 1, y: 19}, {x: 2, y: 20}]}, {row: 0, col: 1, value: [{x: 1, y: 24}, {x: 2, y: 27}]}, {row: 1, col: 1, value: [{x: 1, y: 31}, {x: 2, y: 26}]}, {row: 1, col ...

Issues with reading d3.js visualization data from a JSON file

I am currently working on a data visualization project using D3.js and I started with a basic framework that I found on this link The data for my visualization is coming from a json file containing only two values, a string value and an integer. However, ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...

Show a collection of pictures in an array when hovering over them

My goal is to make all images in an array fade in when a user hovers over the "Class of 2013" section. Currently, I can only display one image at a time upon hover... Is it possible to assign them all to the same <img src... tag? The issue is that I ...

When creating a PDF with Openhtmltopdf, make sure to position the image outside of the CSS @page margins or padding

I am currently working on generating a paged pdf document from html using Openhtmltopdf. My main challenge is placing an image right at the edge of the page, outside of the @page margin. Despite my efforts, including playing with visibility, padding/margin ...

Incorporating React into a non-React website

I am currently working on a project where the server renders all views using the Twig template engine. Therefore, I tend to write all my scripts within the .twig templates. Take, for instance, the aside-buttons.twig template: <div class="aside-butto ...

Position the division block on the page

Is it possible to have 3 div blocks arranged in a specific order? How can I position div 3 below div 1 without changing the layout, as div 3 is responsible for form submission? .div1 { width: 100px; height: 100px; border: 1px solid; } .div2 { w ...

Discovering the indices of undefined array elements in JavaScript without using a loop

Is there a way in JavaScript to retrieve the indexes of undefined array elements without using a loop? Possibly utilizing a combination of map, filter, and indexOf? I have a loop solution that I'm seeking an alternative for - something more concise, ...

What is the best way to avoid duplicating methods within a server application?

Striving to master proper architecture for a node server, I find myself troubled by something. In my efforts to establish a 3-layered design, I have crafted the following folder structure: server/ --|api/v1/vacancies.js --|config/db/index.js --|services/va ...

Retrieve the JSON data from an external URL and showcase it within a div element as simple text

I'm working with an external resource that is similar to and it returns JSON data. My goal is to extract the value of the "result" key from this JSON and display it within a div in HTML (let's call this div "summary"). The value of the result ke ...

How can I iterate through each element of MySelector in the callback function of jquery-ui's draggable function?

When using: jQuery(MySelector).dragabble( start: function( e, ui ) { } ) In the start function: The start event provides $(this) with the current dragged element from MySelector. How can I loop through each element in MySelector to apply additional code ...

What could be the reason for the title template not being implemented in the Next.js metadata for my homepage?

Currently, I am in the process of developing a Next.js project and working on setting dynamic metadata for various pages. Specifically, I want to display the title of my homepage as "Home | My Website", but unfortunately it is only showing as "Home". Below ...

What is the best way to eliminate line-height from the top of text?

I have a design where an image is floated to the left next to text with a line-height of 2. How can I make sure the top of the image aligns perfectly with the top of the text? Changing the line-height to reduce the space between text and image is not fe ...

Building an Array in C++ Containing Class and Derived Objects

My goal is to establish two arrays: regDiceBag, which will consist of 10 base class objects Die, and another array containing 5 base class objects and 5 derived class objects LoadedDie. While I am able to initialize the first array using Die[] regDieBag[10 ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

Are max-width:auto and max-width:100% the same thing?

Does max-width set to auto have the same result as setting max-width to 100% If not, what is the distinction between them? ...

Retrieve the names of columns from a variable by parsing JSON data

I have a variable that stores all the subject names which are also column names in a table. Now that I have captured all the column names in a variable, I want to use this variable in a select statement. Using Ajax success:function(result) { console ...

Building an accordion collapse feature in HTML using CSS and JavaScript

I've been working on creating an accordion interface, but I'm facing an issue where only the first collapsible button works properly. The rest of the buttons are not functioning and don't even appear on the page. When I remove the CSS styli ...