Utilize data attributes in VueJS to dynamically style elements

Is there a way to utilize the data() values within the <style>..</style> section? I have experimented with different combinations (using/omitting this, with/without {{brackets}}, etc.) but haven't been successful. Interestingly, when I manually input a value like '#f00', it works perfectly fine.

My template structure looks like this:

<template>
 <ul class="striped">
     <li>foo</li>
     <li>bar</li>
     <li>foobar</li>
</ul>


</template>

<style>
 ul.striped> li:nth-of-type(odd) {
    background-color: this.colors[0].backgroundcolor;  //dynamic value fetched from data()
}
</style>

<script>

  data() {
    return {

        colors: [{'backgroundcolor':'#def'}], //simplified version for clarity
[..]
</script>

Answer №1

Vue 3.2 has introduced a new feature called State-Driven Dynamic CSS, which allows you to easily apply dynamic styles based on the component's state:

<template>
    <ul class="striped">
        <li>foo</li>
        <li>bar</li>
        <li>foobar</li>
    </ul>
</template>

<style>
    ul.striped> li:nth-of-type(odd) {
        background-color: v-bind('colors[0]')
    }
</style>

<script>
    data() {
        return {
            colors: ['#def'],
        }
    }
</script>

For Vue 2 users, you can achieve similar functionality using CSS custom properties:

<template>
    <ul class="striped" :style="`--color: ${colors[0]}`">
        <li>foo</li>
        <li>bar</li>
        <li>foobar</li>
    </ul>
</template>

<style>
    ul.striped> li:nth-of-type(odd) {
        background-color: var(--color)
    }
</style>

<script>
   export default {
      data() {
        return {
            colors: ['#def'],
        }
    }
   }
</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

An issue occurred during rendering: `TypeError: Unable to retrieve the length property of an undefined value`

I want to display an overlay only when there is text in my search input. Below is the template for my input field: Input.vue: <template> <div> <input v-model="query" class="input" placeholder="Global search..."></input&g ...

How to Make a React JS Component Shift to the Next Row as the Window Shrinks

I am facing an issue with the layout of my product detail page. Currently, I have two components - an image gallery on the left and product information on the right. However, when the window size gets smaller, I want the product information component to mo ...

Guide on creating a hand-drawn pencil circle using only CSS!

Is anyone familiar with how to create a hand-drawn pencil circle hover effect using pure CSS, without relying on SVG like the one featured on CodeMyUi? I've seen examples accomplished with SVG, but I'm specifically interested in achieving it usin ...

Is it possible to modify content in a Laravel post using formData?

Working on a social network, I encountered an issue when trying to enable post editing. The error message displayed is: message: "This action is unauthorized." Despite following the flow of sending data through Axios calls and defined routes to the contr ...

What is the accurate way to retrieve the icon path for 'manifest.json'?

Within my manifest.json file, I have the following code: "icons": [ { "src": "/static/img/icons/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/static/img/icons/android-chrome-512x512.png", "sizes": "512x512", ...

Adjust the CSS of the currently dragged item using jQuery sortable

I am currently using jQuery-ui sortable and facing an issue with changing the appearance of a dragged item. I would like the text value of the component inside the red background container to be displayed while dragging. Can someone please assist me with t ...

Detecting server errors in Nuxt.js to prevent page rendering crashes: A Vue guide

Unique Context This inquiry pertains to a previous question of mine, which can be found at this link: How to handle apollo client errors crashing page render in Nuxt?. However, I'm isolating the focus of this question solely on Nuxt (excluding apollo ...

Using app.js in a blade file can cause jQuery functions and libraries to malfunction

In my Laravel application, I am facing an issue with my vue.js component of Pusher notification system and the installation of tinymce for blog posts. Adding js/app.js in my main layout blade file causes my tinymce and other jQuery functions to stop workin ...

I am facing hurdles with firebase permissions as it is not granting me the necessary access

firebase.database().ref('meetups').push(meetup) .then((data)=> { console.log(data) commit('createMeetup', meetup) }) .catch((error) => { console.l ...

Why aren't Material UI v5 styles being applied to the class?

I have been attempting to customize the MUI slider by applying styles using the className prop. However, I am facing an issue where the styles assigned to the main class are not being applied, but other styles such as the 'hover' state are workin ...

Tips for recalling the display and concealment of a div element using cookies

My HTML code looks like this: <div id='mainleft-content'>content is visible</div> <div id="expand-hidden">Button Expand +</div> To show/hide the divs, I am using JQuery as shown below: $(document).ready(function () { ...

Could an average user potentially access a hidden button meant only for management by examining a website and discovering how to activate it?

Create a website catering to both regular users and management. For instance, normal users are identified as 1, so if their account ID is also 1, they can access a page with limited functionality. Similarly, management is identified as 2, and they too acce ...

How can I resize an element using jQuery resizable and then revert it back to its original size with a button click?

I need help figuring out how to revert an element back to its original size after it has been modified with .resizable. I attempted the following: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="//code. ...

Creating a unique function to map an array in VueJS specifically designed for table manipulation

I am currently working on displaying and sorting data in a bootstrap table within VueJS. My goal is to change the date format within an array retrieved from an API endpoint. The original date format is in "January 21, 2010" and I need it to be in "MM/DD/Y ...

Uniformly sized text containers and buttons

Seeking assistance to align a text field and a button in a way that they appear as a combined element. The desired look is shown below (screenshot taken from Chrome Linux): However, when viewed in Firefox Linux, the button is slightly taller by two pixels ...

separating kids with selectors

What is the recommended method for adding borders between children of various elements within a div? In the example below, there should be borders between p,div and div,img. <div id="list"> <p>child 1</p> <div>child 2</ ...

Loading dynamic CSS on WordPress frontend only

I am facing an issue with the dynamic css file in my WordPress theme that is loaded using Ajax. The problem is that it also loads this dynamic css file for the backend. Can someone help me modify my code so that it only loads the dynamic css file for the f ...

Unable to customize the button color within the Bootstrap framework

This button was created using Bootstrap. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <lin ...

Adjust the color of the navbar only after a user scrolls, with a slight delay rather than

My code changes the navbar colors when I scroll (200ms). However, I would like the changes to occur when I am slightly above the next section, not immediately. In other words, what adjustments should I make to change the color in the next section and not ...

Using RadStyleSheetManager for Optimizing CSS Caching

After implementing the RadStyleSheetManager in my master pages using the given code snippet, I noticed a significant improvement in the performance of my web application. In Internet Explorer 8, the number of dynamically generated WebResource.axd files had ...