DEV Community

Karim Hossenbux
Karim Hossenbux

Posted on

3 3

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 đź‘Ś

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
hmaesta profile image
Hugo Maestá •

You can use <component> too.

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs