Reputation: 274
let's we have a data variable and i want to use this data variable for my style.
data()
{
return{
selected:{
index: 2
}
}
}
<style>
.parent-table >>> .table-row:nth-child(/* here i want to pass selected.index */) {
background: red;
}
</style>
My use case is that i have a table component used in my landing page . I want to change background of selected row of table from my landing page.
Upvotes: 4
Views: 735
Reputation: 914
I don't know how to explain it. but here's how to pass 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
}
}
}
Example of accessing 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 make the props if you only want to get the index
from your data
Upvotes: 5
Reputation: 27232
I don't think we have any solution as per your requirement in Vue 2
. In Vue 3.2
, They introduced this feature which enables component state-driven dynamic CSS values in <style>
tags. You can read that out here
.
After understand your exact requirement and post spending few hours on this requirement, Here I am coming up with the solution in JavaScript way as we can't use dynamic variables in CSS nth-child
selectors. You can have a look in this SO post : Is it possible to use CSS vars in CSS3 selectors?
Looks like you have to do update the style of nth-child
in pure JS way.
Working Demo :
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>
Upvotes: 6
Reputation: 96
this is how you pass a data property to a css property.
<script>
export default {
data: () => ({
color: 'red',
}),
};
</script>
<style scoped>
.card-text-color {
color: v-bind(color)
}
Upvotes: 2