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

How about this: "Leveraging the power of #IEroot to achieve a

Has anyone successfully implemented the IE CSS hack #IEroot? I came across it while reading this informative article, but unfortunately, it doesn't seem to be working for me. I'm currently trying to resolve an inline styling bug in order to achi ...

Is there a way in WebStorm to create a "virtual" folder for conveniently organizing and hiding config files, or perhaps a feature that allows for easily toggling visibility of certain files?

I have a strong dislike for having all my configuration files cluttering up the root directory. These files are usually set up at the beginning of a project and rarely need to be changed. While I can hide them in WebStorm, it becomes a hassle to unhide the ...

Display a substitute image if there is no internet connection available to load the Google Map Canvas

I have a WebApp that runs locally, but it's possible that users may not always have access to 3G/WiFi when using the app. This means that the Google Map will not load without an internet connection since it requires the web API. In order to provide a ...

Modify styling of complete list upon clicking in React

For my latest project, I developed a basic todo application using React. One of the key features is that when a user clicks on a checkbox, the corresponding todo item's CSS changes to show a strike-through effect. Additionally, a button appears on hov ...

What is the best way to incorporate three divs into a single line while maintaining a responsive design

Struggling with adding a logo above a login form? As a PHP developer without design expertise, achieving a responsive layout like the image below may seem daunting. To create this layout, consider using the following code: <style> .container { ...

The WebApi endpoint is not being accessed when deployed on the IIS server, even though it functions properly on the local host

Issue with Web API Endpoint not being triggered after deploying solution to IIS server Working endpoint : https://localhost:44335/Api/Course/GetStudents Endpoint not functioning correctly: Ajax Code function GetStudents(IsEdit) { $.ajax({ ...

How to Utilize Knockout's BindingHandler to Integrate JQuery.Datatables Select Feature?

I've developed a custom KO bindingHandler (view it here) to assist in updating the DataTable. The documentation for JQuery.DataTable.Select regarding how to access data requires a handle. You can see the details here. var table = $('#myTable&a ...

Clearing the contents of unselected ajax .tabs() when a new tab is chosen

I need assistance with ajax .tabs() and how to clear or remove the contents of unselected tabs. I have already explored the jQuery website for a solution and came across this event, but I am unsure what steps to take next: $( ".selector" ).bind( "tabssele ...

How to eliminate background after Ajax call is done using jQuery?

After successfully creating my own tooltips with jQuery and Ajax to pull content from an external file, I encountered a problem. I have a loading.gif animation in the background of the container that I want to remove once the ajax content loads. Can anyone ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Steps for embedding a font in a .pptx file

While working on creating a .pptx file using ASPOSE.Slides, I encountered some issues with embedding fonts. As an alternative option, I am looking for suggestions on how to embed custom fonts in a .pptx file using Apache POI or other methods. If you have ...

What methods can I employ to utilize the name attribute for POST requests instead of the ID attribute in TinyMCE?

My inline TinyMCE form sends content to qry.php with the key "edit_me". I prefer the default behavior of sending content using the name attribute instead. <script type="text/javascript"> tinymce.init({ selector: '#edit_me', ...

delay of Paypal API disbursement for transactions with a range of money values

After browsing through various resources such as this link, that link, and another one on the PayPal developer website, I attempted to implement a payment processing system that allows users to approve a preset amount of money. Similar to services like Ube ...

The AngularJS 2 application reports that the this.router object has not been defined

My function to sign up a user and redirect them to the main page is implemented like this: onSubmit(){ this.userService.createUser(this.user).subscribe(function (response) { alert('Registration successful'); localStor ...

D3 Chart: What is the best way to insert images into a node?

Within the jsFiddle demo provided in this query, there is code displayed. I am curious about how I can assign images to each node. var graph = { "nodes":[ {"name":"1","rating":90,"id":2951}, ] } You can access my jsFiddle Demo through this ...

Encountered an issue while trying to reset the dropdown menu values on a Dash application when utilizing a clear button

I'm attempting to add a clear button for users to reset the values in a dropdown menu. However, when I run the application, I encounter the following error preventing me from selecting an option in the dropdown: Unable to access property 'leng ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

Iterate through a intricate array of JavaScript objects to extract their values

Looking for ways to extract total calorie and nutrition information from a large document displaying the nutritional data of a simulated recipe. Please review the codesandbox json file first. The objective is to capture the total calories and nutritive c ...

After retrieving a value from attr(), the object does not have the 'split' method available

I need to implement the split method on a variable fetched using attr. This is the code snippet I am attempting: $(document).ready(function() { $('.some_divs').each(function() { var id = $(this).attr('id'); var ida = ...