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

Styling in sass gets even more powerful when using custom selectors that are

Using these mixins makes it easy to work with BEM syntax in sass 3.3.2: =b($name) .#{$name} @content =e($name) &__#{$name} @content =m($name) &--#{$name} @content +b(menu) +e(item) color: grey +e(item) +m(alert) ...

Toggle css comment line using gulp

Is it possible to temporarily deactivate a particular CSS comment on a specific line using Gulp and then reactivate it after completing a build task? As an illustration, I am interested in deactivating the @import 'compass/reset'; statement loca ...

Ensure that the user remains within the current div when they click the submit button, even if the textbox is

For the past 48 hours, I've been grappling with an issue on my HTML page that features four divs. Each div contains three input fields and a button. The problem arises when a user leaves a text box empty upon submitting - instead of staying in the sam ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

Transforming Button style in jQuery Mobile version 1.3.0

There are reports of a new function in jQuery Mobile 1.3.0 that allows for dynamically changing button themes using JavaScript: http://jquerymobile.com/blog/2013/02/20/jquery-mobile-1-3-0-released/ However, upon attempting to run the provided code snippe ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...

Writing CSS rules for generating HTML code when sending emails through the command line in Go

When trying to compose HTML with CSS for email delivery using Go command line execution, errors related to CSS properties are popping up. For instance, it's showing "not found" error in the terminal for properties like background: rgb(255, 255, 255) o ...

floating downward inside the container

Check out my website at . Everything looks great in Firefox, but when I view it in IE, the "top" button that should be floated inside the h2 titled "Unit 301: Pre-production skills" is floating to the right and getting pushed outside of the heading. Any i ...

Show the image on top of the div block as the AJAX content loads

Implementing this task may seem easy and common, but I am struggling to figure it out! What should take five minutes has turned into an hour of frustration. Please lend me your expertise in getting this done. I have a div container block: <div cla ...

What value is used as the default for justify content?

MDN states that the default value of justify-content is normal, even though it's not listed in the accepted values. What exactly does a normal value mean? normal This means that items are packed in their default position as if no justify-cont ...

Styling text using CSS depending on the displayed text

Utilizing Awesome Tables (AT), I am extracting data from a Google Sheets document to display on a website. The HTML template in the sheets is used for formatting the data, specifically focusing on the table output with inline CSS styling. Since the templat ...

Generate a scrollable element and adjust its dimensions to fit the window

Currently, my webpage features a header at the top followed by a sidebar on the left and the main content area on the right. I am looking for a solution that will allow the main content area to scroll independently from the side bar. --------------------- ...

Surprising spacing found between CSS header elements

As I am in the process of redesigning a website, I have encountered an issue with certain elements in the header section. Specifically, the header consists of a logo, some text, and a navigation bar. There seems to be a thick gap between the bottom of the ...

ID is not receiving the CSS styles

I'm having trouble applying my CSS to a specific img ID element on the page. I've been trying to solve this for about 30 minutes with no luck. The strange thing is, I have two other elements with the same HTML and CSS that are working correctly. ...

populating all available space in layouts using bootstrap columns

I am attempting to create a grid layout using bootstrap, but I am facing an issue with positioning one of the columns. I have tried adjusting the placement of the divs and using offsets/pulls, but so far I have not been successful. To explain what I am a ...

What is the process for modifying the path and polyline in an SVG file?

I have a pair of SVG icons that I am working with. Recent Update: Icon One Icon Two One question that I have is whether it is possible to create both icons using the same HTML markup? For instance, can I use something like: <g> <circle ... ...

What is the best way to center align the div container horizontally?

Trying to center the #container but all methods have failed. How can I achieve centering using only CSS? body { text-align:center; } <div id="app"> <div id="container"><div id="container_red" style="position:absolute;left:0"> ...

Conceal or style the filter panel in a DT datatable

Here is an example to consider: library(DT) L <- 10 datatable( data.frame( var1 = sapply(1:L, function(x) paste("<X>",paste0(x, letters, LETTERS, "\n", ...

Utilize the Tab feature effectively in Impress.Js

Currently, I have disabled the Tab key in Impress.js so that it only moves to the next slide. However, when I try to focus on links and delete this code to let it behave normally, Impress.js crashes. Has anyone found a workaround for this issue? Appreciat ...

Navigate the cursor beyond the span within the content that is editable

I am currently developing a tag input system for a template builder. My main focus right now is on assisting the editor in distinguishing between regular text and formatted text. I am structuring it similar to WordPress shortcodes, where a templated elemen ...