VueJS: using dynamic class names within the style attribute

Within my VueJS application, I have implemented Materializecss modals within single page components. Each modal requires a unique dynamic ID due to the application's requirements. The code snippet below showcases this:

<template>
    <div :id="modal_id" :class="'modal '+modal_id">
        <div class="modal-content">
            .... stuff here
        </div>
        <div class="modal-footer">
            <a class="modal-close waves-effect waves-green btn-flat">Exit</a>
        </div>
    </div>
</template>

<style type="text/css" scoped>
    .modal {
        width: 90% !important;
        height: 100% !important;
    }

    .modal_id 
    {
        background-color: black;
    }
</style>

<script type="text/javascript>
    import pdf from 'vue-pdf'

    export default {
        data: function() {
            return {
                modal_id: 'ViewPdf_'+this.$root.g(),    // this.$root.g() returns a unique integer          
            }
        },
    }
</script>

I am curious if it is achievable in Vue to dynamically modify the custom class name within the <style></style> tags to match the generated class name when the component is mounted. If not, I would appreciate any suggestions for potential workarounds.

<style type="text/css" scoped>
    .modal {
        width: 90% !important;
        height: 100% !important;
    }

    .modal_id  
    {
        background-color: black;
    }
</style>

Answer №1

When all the CSS is within your Vue component, it is easier to generate style information directly in your component instead of trying to align css selectors based on DOM id.

Instead of using:

<div :id="modal_id" :class="'modal '+modal_id">

You can use:

<div :id="modal_id" :style="modalStyle">

Then, inside your component, create a computed property for the style following the guidelines at https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-Inline-Styles

For instance:

computed: {
  modalStyle: function () {
   return {backgroundColor: 'black'};
  }
}

Answer №2

To create a dynamic class name for a specific modal, you can establish a computed property that reacts to changes in the modal_id.

<template>
    <div :id="modal_id" :class="className">
        ...
    </div>
</template>
<script type="text/javascript>
    export default {
        data: function() {
            return {             
            }
        },
        computed: {
            className: function () {
                if (this.modal_id === <your modal_id1>) return 'class1';
                else if (this.modal_id === <your modal_id2>) return 'class2';
            },
            modal_id: function () {
                return 'ViewPdf_'+this.$root.g()
            }
        }
    }
</script>
<style>
    .class1{}
    .class2{}
</style>

If you want the modal_id to be dynamic as well, it should also be defined as a computed property.

Answer №3

Indeed, it is possible to modify the css property name using JavaScript when utilizing an external css file. I have provided a straightforward example below where I demonstrate how I altered the css name to apply its style to the second paragraph.

//determining the index of the stylesheet based on load order
var cssIndex = 0;
var cssRules = (document.all) ? 'rules' : 'cssRules';

function changeClass() {
    for (i = 0, len = document.styleSheets[cssIndex][cssRules].length; i < len; i++) {
        if (document.styleSheets[cssIndex][cssRules][i].selectorText === ".text") {
            document.styleSheets[cssIndex][cssRules][i].selectorText = ".text2";
            return;
        }
    }
}
.text {
text-align: center;
}
<button onclick='changeClass()'> Change css property class name </button>
<p id="1" class="text">This is text class</p>
<p id="2" class="text2"> This is text2 class</p>

You can easily implement this technique in your Vue code.

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

Top recommendation for transferring data from Laravel to Vue component

Here lies the essence of my coding prowess <div id="app"> <CustomComponent bam-wam="ham" /> </div> This is where my VueJS magic happens <script> export default { name: "ExampleComponent", props: [ ...

What steps can I take to resolve the CSP errors I am experiencing?

I am currently working with NextJs@12 and I am attempting to set up CSP for my application. Unfortunately, I keep encountering errors in my console and I cannot figure out where I am going wrong. Below is the current policy that I have in my next.config fi ...

Optimizing Your HTML/CSS/JavaScript Project: Key Strategies for Modular

When it comes to web frontend projects (html/css/javascript), they are often perceived as more complex to read and maintain compared to Java/C#/C/C++ projects. Is it possible to outline some optimal strategies for enhancing the readability, modularizatio ...

Which symbol or character corresponds to the public "get symbol" method?

While going through some Typescript code, I came across a line that is giving me trouble to understand. const symbol = Symbol.for('symbolname'); class Something { public get [symbol]() { return true; } ... } I am confused abou ...

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

Having trouble locating the data-testid attribute within a Vue Component using Jest

I need assistance in constructing a test that specifically selects an element utilizing the data-testid attribute. The scenario involves a BaseTile component structured as follows: <template> <div data-testid="base-tile-icon&quo ...

Using jQuery to decrease the size of a div element containing an image

Hello everyone! I have an image inside a div and I am currently moving it down at a specific time using a delay. My question is, how can I make the image shrink as it moves down the screen until it eventually disappears completely at a set location? Curre ...

Animate sliding bar to move from the left using jQuery

I am currently experiencing an issue with a sliding animation on mouseover in the navigation. The animation works fine, but the problem arises when I hover over any menu item - the sliding bar starts from the very left instead of starting where the navigat ...

What are the steps to implement timer control in Ajax using JavaScript?

Hello, I have been trying to establish communication with the server through my application. To achieve this, I made a call to the webservice using AJAX. Now, I am looking to incorporate a time interval in AJAX. Can anyone kindly provide guidance on how ...

Top solution for preventing text selection and image downloading exclusively on mobile devices

My plan is to use the following code to accomplish a specific goal: -webkit-touch-callout:none; -webkit-user-select:none; -khtml-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none; -webkit-tap-highlight-color:rgba(0,0,0,0); I& ...

Vuejs did not have these dependencies within its codebase

There appear to be missing dependencies: * -!../../../../node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../node_modules/postcss-loader/src/index.js??ref--8-oneOf-1-2!vuetify ...

Why does the API in Next Js get triggered multiple times instead of just once, even when the strict mode is set to false?

React Query Issue I am currently facing an issue with React Query where the API is being triggered multiple times instead of just once when the selectedAmc value changes. I have tried setting strict mode to false in next.config.js, but that didn't so ...

How to dynamically set Bootstrap navbar item as active based on current filename?

Currently, as I construct my website using the bootstrap framework, I am facing a minor challenge. I want to activate a menu item based on the filename by utilizing an if statement. For instance, when the filename is "about," the "about" tab should be act ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

Obtain a socket object from the Vuex store

I'm currently using vue socket io to receive data from a socket. To get the data, I utilize a query like this: // ioinstance import io from 'socket.io-client' const restaurantId = localStorage.getItem('restaurant-id') const socket ...

Establishing global credentials in VueJS using Axios

When working in main.js, I included the following code: axios.defaults.withCredentials = true; Although this should make it work, I found that the cookies were not being sent to the back end. I inspected the request header and noticed something strange: ...

Facing some unexpected issues with integrating Django and AngularJS, unclear on the cause

In my simple Angular application, I encountered an issue. When I run the HTML file on its own in the browser, the variable name "nothing" is displayed as expected. However, once I integrate the app into Django by creating a dummy view that simply calls a t ...

How to use getBoundingClientRect in React Odometer with React Visibility Sensor?

I need help troubleshooting an error I'm encountering while trying to implement react-odometer js with react-visibility-sensor in next js. Can anyone provide guidance on how to resolve this issue? Here is the code snippet causing the problem: https:/ ...

Obtain JSON data instead of XML data from a web service through Ajax with the option 'contentType' set to 'false'

Upon making an AJAX call to send an image file to one of my web service (.asmx) methods, I encountered a problem where the web service returns XML instead of JSON. This issue arose because I needed to set the contentType to false, in order to successfully ...

Customize your MUI Select to show the selected value in a different way within the Input field

I have a collection of objects and I am looking to link multiple attributes of the object in MenuItem, but I only want one attribute to be displayed in Select https://i.sstatic.net/kDKLr.png The image above displays "10-xyz" in the select display, when i ...