Reputation: 469
So I want to use some Vue data/prop variables in the <style>
tag placed at the bottom of the component.
So let's say I have a component like this:
<template>
<div class="cl"></div>
</template>
<script>
export default {
data () {
return {
val: '30px'
}
}
..
}
</script>
<style>
.cl p{
height: 30px;
}
</style>
I want to somehow use the val data variable in the <style></style>
such that I can style it that way.
Now I know doing this <div :style="{'height':val}"></div>
is how you style using vue props/variables. But that only sets the style of that div. I want all the p tags or any tags inside my div to have a certain style, and that can only be done by declaring it as a class.
There is also another way of doing it by defining the class and making it active (true/false) value, like : <div :class="{'cl': someBoolVariable}"></div>
. But what if I want it to be dynamic enough to change the height based on some computation/value passed from parent component?
I need something like this, if possible:
<style>
.cl p {
height: val;
}
</style>
Can anyone suggest a way of doing this, if possible? Or a simple work around to achieve this?
Upvotes: 3
Views: 8603
Reputation: 383
In Vue 3 you can do it in a much simpler way by using v-bind on styles:
<template>
<div class="text-area">Colored text</div>
</template>
<script setup lang="ts">
const color = '#ebae34'
</script>
<style scoped lang="scss">
.text-area {
color: v-bind(color);
}
</style>
Upvotes: 0
Reputation: 4657
You can achieve it using a CSS variable on your main div
element
<template>
<div class="cl" :style="'--p-height: ' + val"></div>
</template>
<script>
export default {
data() {
return {
val: '30px'
}
}
}
</script>
<style>
.cl p {
height: var(--p-height);
}
</style>
Here's a jsfiddle
Upvotes: 11