A guide to assigning multiple classes to an element in Vue.js depending on the props!

Take a look at my code to grasp the issue.

<template>
    <div class="header" 
        :class="flat ? 'flat' : null"
        :class="app ? 'app' : null">
    </div>
</template>

<script>
    export default {
        props: {
            flat: {
                type: Boolean,
                default: false
            },
            app: {
                type: Boolean,
                default: false
            }
        }
    }
</script>

<style lang="scss">
    .header {
        width: 100%;
        height: 55px;
        background: white;
        box-shadow: 0px 3px 6px #ccc;
        transition: .8s ease-in-out;

    }
    .flat {
        box-shadow: none;
    }
    .app {
        padding-left: 10%;
        padding-right: 10%;
    }

</style>

Here we have the flat prop triggering a class for displaying or hiding box-shadow, and the app prop adding some padding to the header. However, the limitation is that only one :class can be used in an element. Is there a workaround for this?

Answer №1

Vue offers various methods to achieve the desired outcome.

1. Utilizing an array of classes

<div 
  class="header" 
  :class="[flat ? 'flat' : null, app ? 'app' : null]"
></div>

2. Implementing an object

<div 
  class="header" 
  :class="{flat: flat, app: app}"
></div>

In this case, only properties with truthy values will be applied as classes.

2.1 For ES6 users You can use the object property value shorthand method.

<div 
  class="header" 
  :class="{flat, app}"
></div>

Bonus Tip

If needed, you can also combine the array and object approach.

<div 
  class="header" 
  :class="[{flat, app}, someOtherClass]"
></div>

Answer №2

Try combining both classes within the same class attribute like this:

<div class="header"
  :class="{ 'flat': flat, 'app': app }"
>header</div>

For more information, refer to the official documentation

Answer №3

If you want to achieve a similar result as @Boussadjra Barhim's answer, you can create a method that returns an object with specified properties.

//This method sets the class based on the provided values
setClass: function(flat, app){
    return {
      flat: flat, 
      app: app
    }
}

To use this method, simply call it like this:

<element :class="setClass(flat, app)" />

Alternatively, if you need to perform additional operations before returning the object, you can modify the method accordingly:

setClass: function(flat, app){
    //Perform any necessary operations here
    return {
      flat: flat, 
      app: app
    }
}

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

Ways to position a single item in the middle of a multi-column layout

I need help with aligning dynamic images in a 2-column layout. What's the best way to center a single image or collapse the columns when there's only one image? Currently, the single image is always placed in the left column. Is there a CSS-only ...

Exporting data from a jQuery table to CSV format

I have customized the jQuery Table to CSV Plugin so that it triggers a browser download of a CSV file. The original function was: function popup(data) { var generator = window.open('', 'csv', 'height=400,width=600'); ge ...

The credentials in AWS S3Client are failing to load correctly

I encountered an issue with the S3 Client from aws sdk v3: When using the S3Client as outlined in the documentation and providing credentials via environment variables, I received an error message stating The AWS Access Key Id you provided does not exist ...

Can the <container> block be positioned beneath the <header> block?

header { background: blue; color: white; width: 100%; } .container { background: green; text-align: center; width: 100%; height: 100px; transform: skew(0, -10deg); color: white; position: relative; top: 55px; } .container .home{ p ...

Is there a specific HTML tag available to instruct the browser to cache my HTML and/or CSS files for future use?

Up to this point, my research has indicated that enabling JavaScript and CSS browser caching typically requires server side settings such as .htaccess. Is there any HTML tag or configuration within the HTML page or JavaScript that can instruct the browse ...

Having trouble displaying a set of data points in a React component

Exploring React, I have built a test app and performed an API call to fetch a large JSON object. After breaking it down into 10 arrays with 3 props each, I am now facing a challenge in sending this data to another component. Despite being able to log the ...

How to Retrieve Results Using Async in Node.js Module?

I am currently developing an internal NPM module for my company to enable applications to communicate with a hardware device using an existing library. The challenge I am facing is implementing a method that must execute asynchronously. This function shoul ...

Troubleshooting a mapping problem with CSS elements

While building my website, I have successfully mapped the elements by ID for all alphabet letters except A. When clicking on the letter A, it does not go to the respective elements. Can anyone please help me find a solution? Visit this link for reference ...

Creating a responsive design with dynamic width using HTML and CSS to handle overflow situations

Struggling to figure out how to achieve this in html, I would like the solution to be limited to just html + css. Javascript/jquery is being utilized on the site, yet I don't want my design to rely on javascript. Section A contains a list of variable ...

What is the best way to line up several elements in a single column?

I am facing a layout challenge with two objects inside a column - a paragraph and an image. I need the image to be positioned at the bottom and the paragraph at the top. I have tried using various Bootstrap classes like "align-items-between" and "align-sel ...

Is there a way to modify the color scheme of the hamburger icon

I'm experiencing difficulties changing the color of a hamburger icon. I've searched for the specific code responsible for the color change, but I haven't been able to locate it. Ideally, I want the color to be white, but on small screens, i ...

Exploring ways to retrieve texture dimensions using Three.js

Can someone please advise me on how to retrieve the dimensions of a texture? I have set my texture using the following line of code: const texture = THREE.ImageUtils.loadTexture(src) Do I need to load the image in order to obtain its dimensions (and can ...

Unable to transfer data successfully from popup to extension.js

I am currently developing a browser extension using Crossrider and I'm facing an issue with sending data from the popup to extension.js Here is my code for the popup: <!DOCTYPE html> <html> <head> <!-- This meta tag is relevant ...

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

Tips for managing CSS/style conflicts in JavaScript/AngularJS applications

I am new to AngularJS and I have a requirement to assign CSS properties to a component at the JavaScript file level. When I debug my code after applying the CSS styles to the component, I can see that all the applied CSS properties are behaving as expected ...

Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed. var aSteps = [ { "x": "800", "y": "0" }, { "x": "800", "y": "500" }, { "x": "0", "y": "500" ...

Using CSS3 translate will result in children becoming relatively positioned

I am facing an issue with a sidebar that contains 2 divs. <div class="sectionsContainer clearfix"><-- Sidebar --> <div class="leftSection pull-left"> <p>Maor</p> </div> <div class="rightSection pu ...

The text in the image caption has been drastically reduced along with the size of the image

Currently, I am dealing with the following code: <div style="min-width: 1000px;"> <p> Some text </p> <div class='div_img_left'> <img src="images/sth.png" alt="missing image" style="max-width ...

Java has trouble decoding non-ASCII characters sent through Ajax

When I send an AJAX request using jQuery post() and serialize, the encoding used is UTF-8. For instance, if 'ś' is input as a name value, JavaScript displays name=%C5%9B. Despite my attempts to set form encoding, it has not been successful. < ...

Is it possible to save or write a text file in the VueJs renderer process without the need to open the dialog box?

Currently, I am working on a project using VueJs + electron, where I need to save a text file to the user's PC without any prompt or dialog box popping up. I am aware of how to do this using require('fs'), but unfortunately fs does not work ...