Utilizing the power of Vue.js 3 to dynamically apply multiple custom classes to a table

I recently started using Vue for my frontend project and I am facing a challenge. I am trying to dynamically add classes to my table based on user input. Currently, I am able to add only one class, but I want to extend this functionality to work with an array of classes. Can anyone provide some guidance on how to achieve this?

Additionally, I would like to include more input options for adding other classes such as table-bordered and table-striped...

<div class="form-check form-switch">
  <input v-model="smallTable.active" type="checkbox" class="form-check-input" id="smallTable" @change="tableStyles()">
  <label class="form-check-label" for="smallTable">
    Small Table
  </label>
</div>

//Table tag
<table class="table table-hover align-middle mb-0" :class="smallTable.smTable">
...

//vue component
data() {
        return {
        smallTable: {smTable: "", active: false,},
      }
}

tableStyles() {
            if (this.smallTable.active) {
                this.smallTable.smTable = "table-sm"
            }else {
                this.smallTable.smTable = ""
            }
            localStorage.setItem("tableStyle", JSON.stringify(this.smallTable));
        },

I am looking for a solution that allows me to have multiple classes in an array like this:

data() {
        return {
        smallTable: [
          {smTable: "", active: false,},
          {bordertable: "", active: false,}
         ]
      }
}

Answer №1

Here are two different methods you can use:

  1. One method involves using a string of classes separated by spaces
tableStyles() {
  this.smallTable.smTable = '';
  if (this.smallTable.active) {
    this.smallTable.smTable += ' table-sm';
  }
  if (this.checkbox1.active) {
    this.smallTable.smTable += ' table-bordered';
  }
  if (this.checkbox2.active) {
    this.smallTable.smTable += ' table-hover';
  }
  localStorage.setItem('tableStyle', JSON.stringify(this.smallTable));
},

  1. The other method involves using an object with boolean switches for each class
// You need to create an object
// with class names as keys and booleans as values, indicating whether the class should be applied or not.

tableStyles() {
  this.smallTable.smTable = {
    'table-sm':       this.smallTable.active,
    'table-bordered': this.checkbox1.active,
    'table-hover':    this.checkbox2.active,
  };
  localStorage.setItem('tableStyle', JSON.stringify(this.smallTable));
},

These methods allow you to dynamically set classes based on specific conditions. Make sure to adjust the conditions to match your own data.

Answer №2

Utilize the ternary condition when binding classes to apply multiple classes to an element. Learn more about it here

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

Transmit a basic JSON object from a Node.js server to an index.html webpage

People often overlook this seemingly simple solution when I search for it on Google. My goal is to send a basic json message or file to my index.html page. Here's the Node.js code: const express = require('express'); const app = express(); ...

AngularJS and Handlebars (npm)

Is it possible for angularJS to function as a substitute for the "view engine" in nodeJS? I am seeking insights on the optimal method to use. (Do MEAN Stack developers utilize view engines? Or do they prefer using res.sendFile along with tools like ui-ro ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

Displaying search results in various Angular components

On my home page (homePageComponent), I have a search feature. When the user clicks on the search button, they are redirected to a different page called the search list page (searchListComponent). Within the searchListComponent, there is another component c ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Using Angular 5 to link date input to form field (reactive approach)

I'm encountering an issue with the input type date. I am trying to bind data from a component. Below is my field: <div class="col-md-6"> <label for="dateOfReport">Data zgłoszenia błędu:</label> <input type="date" formC ...

Switching Over to Burger Menu

I created a burger menu using HTML, CSS, and jQuery that switches from a full-width menu to a burger menu. However, I'm facing an issue with toggling the dropdown when the menu collapses. Here's my code: <!DOCTYPE html> <html> < ...

Chat application using Node.js without the need for Socket.IO

Recently delving into the world of Node.js, I stumbled upon the fs.watchFile() method. It got me thinking - could a chat website be effectively constructed using this method (along with fs.writeFile()) in comparison to Socket.IO? While Socket.IO is reliabl ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

Reorganizing JSON data with ES6 techniques

I have a scenario where I need to update tire quantities in an array like this: tires: [{ name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct2", quanti ...

The functionality to disable the ES lint max length rule is malfunctioning

In trying to disable an eslint rule in a TypeScript file, I encountered an issue with a regular expression that exceeded 500 characters. As a result, an eslint warning was generated. To address this, I attempted to add an eslint comment before declaring th ...

What is the most effective way to delete a single value from a key with multiple values stored in local storage?

This question has come up before, but the solutions provided didn't work for me, which is why I am asking it again. Currently, I am storing values in an array that is then stored in local storage. Here is the object: data.items - 0: {id: 190217270, ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

Adjusting the spacing between a pair of radio buttons within the identical group

Is there a way to adjust the spacing between two horizontal radio buttons? The buttons are part of the same group, and I want to shift the right button ("Clear Selection") further to the right so it aligns with the buttons in another group below. ...

Exploring the methods for retrieving and setting values with app.set() and app.get()

As I am granting access to pages using tools like connect-roles and loopback, a question arises regarding how I can retrieve the customer's role, read the session, and manage routes through connect-roles. For instance, when a client logs in, I retrie ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...

A sleek and streamlined scrollspy that dynamically updates the active class exclusively for anchor tags

Can anyone help me with this coding problem? I'm currently working on a minimalistic scrollspy code that adds an active class when the content is offset.top. The code works fine, but I want to change the active class to apply to the "a" tag instead of ...

Enhance table functionality with AngularJs by implementing expandable middle rows

I am developing a payment platform where users can set up a paymentPlan for a specific paymentMethod and choose the number of numberOfIntallments. The details of the paymentPlan are displayed in a table using ng-repeat. Users can select up to 36 numberOfIn ...

Transfer a Sencha Touch application from iOS to Android and Windows devices

I am a dedicated Android developer who is diving into the world of Sencha Touch, Windows app development, and VisualStudio environments for the first time. Please excuse the detailed explanation of my problem, as I want to make sure all crucial details are ...