DEV Community

Karim Hossenbux
Karim Hossenbux

Posted on

How to inline the style tag in Vue

Let's say you want to target some pseudo element to give it like a dynamic color or something. But you have that color value that come from Vue...

  • You can't use CSS, you don't have access to the color value
  • You can't use v-bind:style on a pseudo element
  • Vue doesn't let you use <style></style> in your template tag, vue-loader or vue-template will filter out any style tag

Solution: Make a little component to output a style tag

main.js

Vue.component('v-style', {
  render: function (createElement) {
    return createElement('style', this.$slots.default)
  }
})

Component.vue (in your <template></template>)

<v-style type="text/css">
  .progress::-webkit-progress-value { background-color: {{ color }}!important; }
</v-style>

I had to use !important with this solution, I saw some people using a unique _uid to target the element properly using <component is="style">, but this one seems faster đź‘Ś

Oldest comments (1)

Collapse
 
hmaesta profile image
Hugo Maestá

You can use <component> too.

<component :is="'style'" type="text/css">
    .element {
        color: {{ style.color }};
    }
</component>