3

I'm writing a Vue component that dynamically renders an SVG. Usually <style> tags are not allowed in Vue templates, but is there any way to allow it in this particular situation?

The following will either throw an error, or generate an svg without the style tag, depending on how your project is setup (Code Sandbox):

<template>
  <svg :width="svgWidth" :height="svgHeight">
    <style>rect{fill:red}</style>
    <rect :height="rectHeight" :width="rectWidth" />
  </svg>
</template>

One obvious workaround is to use inline styling for all elements, but for convenience I wonder if it possible to tell Vue to leave the style tag inside the svg tag alone? (I'm generating both style and SVG elements dynamically, so it would make for a more readable code and a much smaller rendered SVG element.)

I'd like to make the SVG self-contained, i.e. keeping the style tag inside the rendered image.

1 Answer 1

4

To use <style> tags with svgs, you can prefix them by svg:.

Working example:

<template>
  <svg width="100" height="100">
    <svg:style>rect{fill:red;}</svg:style>
    <svg:rect width="20" height="30" />
  </svg>
</template>

Please note that I changed the attributes of your rect as it displayed an empty (0x0) rectangle.

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

2 Comments

Wow, that was easy, thank you! Do you happen to have a link to the documentation on this?
I just though I would use a namespace to prefix the style tag. Take a look at this: w3.org/TR/SVG2/struct.html#Namespace

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.