Using data variables as arguments in the style section of Vue2

Suppose we have a data variable and I want to utilize this data variable for styling purposes.

data() 
{
 return{
        selected:{
         index: 2
        }
     }
}
<style>
.parent-table >>> .table-row:nth-child(/* here I intend to use selected.index */) {
   background: red;
}
</style>


My scenario involves using a table component on my landing page. The goal is to modify the background of the selected row in the table from the landing page.

Answer №1

Unfortunately, there doesn't seem to be a solution that fits your requirements within Vue 2. The good news is that in Vue 3.2, a new feature was introduced that allows for component state-driven dynamic CSS values within <style> tags. You can learn more about this update here.

After carefully analyzing your needs and spending some time researching, I have come up with a JavaScript-based solution since dynamic variables cannot be used in CSS nth-child selectors. For further information, you can refer to this Stack Overflow post:

Is it possible to use CSS vars in CSS3 selectors?

It appears that the best approach would be to update the style of the nth-child using pure JS.

Check out this working demo below:

new Vue({
  el: '#app',
  data: {
    selected: {
      index: 2
    }
  },
  mounted() {
    let listSelector = document.querySelector(`li:nth-child(${this.selected.index})`);
    listSelector.style.backgroundColor = 'lightGreen';
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul>
    <li>First list item</li>
    <li>Second list item</li>
    <li>Third list item</li>
    <li>Fourth list item</li>
    <li>Fifth list item</li>
  </ul>
</div>

Answer №2

I'm struggling to find the right words, but here's a guide on passing variables to style scope

PROPS:

props: {
    bgColor: {
       type: String,
       default: "#ff0000" //RED
   }
 }, 

COMPUTED (variables that can be used as arguments):

computed: {
    tableRowColor() {
      return {
        '--bg-color': this.bgColor,
        '--index': this.selected.index //from your data
      }
   }
}

Here's an example of how you can access the variables inside style scoped:

<style scoped>

     table, td, th {
        border: 1px solid;
     }

     table {
        width: 100%;
        background: var(--bg-color); /*here is how to access the variable */
    }
</style>

note: You don't need to define props if you only need to retrieve the index from your data

Answer №3

Here is a demonstration of passing a data property to a CSS property.

<script>
    export default {
        data: () => ({
            color: 'red',
        }),
    };
</script>
<style scoped>
.card-text-color {
    color: v-bind(color)
}

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

JavaScript (specifically, using jQuery) in conjunction with AJAX

After using validation with jQuery in JavaScript and applying it to ASP.NET controls within an AJAX update panel, I encountered a problem. The validations are working correctly, but the event of the button control is still being executed despite the valida ...

Using browserify "require" in console: A step-by-step guide

My Rails project now includes the browserify and pinyin packages, thanks to the browserify-rails installation. To find out more about the pinyin package, check out this link: https://github.com/hotoo/pinyin var pinyin = require("pinyin"); console.log(pin ...

D3: Ensuring Map is Scaled Correctly and Oriented Correctly

I am attempting to integrate a map into a website using D3 and topoJSON that resembles the following: However, when I create the map with D3/topoJSON, it shows up small and inverted. Even after exploring various solutions (like Center a map in d3 given a ...

The image from the SQL database fails to show up in the detailsView ImageField when using the jQuery lightbox, as well as the asp:Image control

Upon clicking the image displayed in the detailsView ImageField, the jquery lightbox pops up but fails to show the picture. Instead, it displays a red x in the middle of the lightbox. The same issue arises with the asp:Image control within the provided c ...

Issue with Sheetjs: Date format is not recognized when adding JSON data to a

I am struggling to export JSON data to Excel while maintaining the correct date format of 2020-07-30 07:31:45. Despite trying suggestions from a helpful post on sheetjs, I still couldn't get it right. Here is an example of the JSON data: { "so ...

"Commander.js does not process query strings when used in conjunction with node

I developed a CLI tool using commander.js which has been released on npm. This command-line interface utilizes node-fetch to fetch data from an external API. However, I have received reports from some users stating that the query string in the fetch URL is ...

I must duplicate a pattern to accommodate various object dimensions

Let me clarify something. I am faced with the challenge of handling multiple textures, and I already know which method to employ for this task. The solution I identified was to use UV mapping on geometries to repeat textures. However, the issue I'm ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Nextjs is having trouble loading the Infogram script

Struggling to insert an Infogram into my project by pasting the script but it's not working as expected. All other scripts in _app.js are functioning properly, however, this particular script isn't loading the graphic even though it appears when ...

How can I retrieve the input value on the current page using PHP?

Hey there, so I'm pretty new to PHP and I have a question. Is it possible to retrieve the input value from an existing input field on a page using PHP when the page loads, and then assign that value to a variable? For instance, let's say I have ...

Experiment with a drag-and-drop interaction using vue-test-utils

I am interested in testing user interaction with drag and drop functionality on a DOM element. While Vue test utils offers the trigger method for events like click, such as wrapper.find('#someId').trigger('click'), I am having trouble ...

Creating ellipses using Three.js with a specified list of points

Currently, I am working on a solar system model using Three.js. I have a function that calculates the position of the planet based on the day, but I am struggling to draw the correct elliptical orbit for the planet using a list of points generated from tha ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

Stop the interval when hovering and start the interval when moving the mouse away

I've managed to create a carousel that automatically slides every 5 seconds, with manual buttons to navigate the slides. My goal is to pause the scrolling when the mouse hovers over a slide and resume once it's no longer hovered. Currently, my s ...

Click on the image to open it in the modal window

I'm looking for a way to display an image in a modal using Foundation. Currently, I have the following code: <img src="images/medium/Pluto.jpg" style="margin-left:10px;margin-right:10px; max-height:150px;max-width:150px"/> as well as <di ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

The spinal cord of design inquiry

I am currently working on a Backbone view called MainMenuView. Within this, the MainMenuModel consists of an array of sub-models known as ItemModel. The main menu is divided into two pages and includes next and previous buttons for navigation. The first pa ...

Creating intricate JavaScript objects for JSON API integration can be accomplished by following these steps:

Here is a sample JSON structure used for querying an API: "order_items": [ { "menu_item_id": "VD1PIEBIIG", "menu_item_name": "Create Your Own", "modifiers": [ { "modifier_id ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

The $or operator in mongoose falls short in providing complete data when paired with the find() method

I am currently utilizing the find method in conjunction with the $or operator to search the database for any duplicate data within this specific line. const duplicate = await NewItemsData.find({ $or: newItems }); Upon inspecting the variable in the consol ...