3

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?

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

5 Comments

Can you also do this: `:style="{'--p-height': val}"?
@hrishikeshpaul Yes, it's the same
This does not work! checked jsfiddle and that is also not working. am I missing something?
@spidey dont' know why but in the jsfiddle vue was removed. If you select "vue 2.2.1" in "framework and extensions" in the menu just above the script box and run again it works.
I have updated the jsfiddle with a working one
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.