Skip to content

SVG Injector

SVGInject is a Vue component based on the open-source library svg-injector. It allows you to import SVG files via the <img> tag and automatically replaces them with inline <svg> code once loading is complete.

The core advantage of this approach is that it enables externally imported SVGs to respond to CSS style controls such as fill and stroke, just as if they were written directly into the HTML.

Basic Usage

Basic Injection

Simply pass the path of the SVG file via the src attribute. The component will automatically load and inject it into the page.

vue
<template>
  <div class="icon-box">
    <TuiSvgInjector src="/assets/icons/rocket.svg" />
  </div>
</template>

Style Control (CSS Styling)

You can add a class name to the final generated <svg> tag using the naming attribute. This allows for easy icon color changes via CSS.

vue
<template>
  <div class="demo-box">
    <TuiSvgInjector 
      src="/assets/icons/heart.svg" 
      naming="my-active-icon" 
    />
  </div>
</template>

<style>
/* Directly control the internal color of the SVG via CSS */
.my-active-icon path {
  fill: #ff4d4f; /* Red fill */
  transition: fill 0.3s;
}

.my-active-icon:hover path {
  fill: #cf1322; /* Darkens on hover */
}
</style>

Technical Notes

⚠️ DOM Replacement Mechanism and Ref Limitations

The working principle of this component is as follows: it initially renders an <img> tag. Once the SVG content is finished loading, the underlying library will completely replace that <img> tag with inline <svg> code.

Consequently, you cannot obtain a persistent DOM reference through Vue's ref attribute. The initial img element pointed to by the ref is removed from the DOM tree after injection is complete, and the new svg element is not automatically managed by Vue's template ref. If you need to manipulate the injected SVG DOM, it is recommended to use native DOM queries or handle it within the @load callback.

Load Callback

Since SVG injection is an asynchronous process involving a network request for the SVG file, the component provides a load event that triggers after the injection and DOM replacement are finished.

vue
<script setup>
const handleSvgLoaded = () => {
  console.log('SVG has been successfully injected into the page; DOM operations can now be performed.');
}
</script>

<template>
  <TuiSvgInjector 
    src="/assets/icons/chart.svg" 
    @load="handleSvgLoaded" 
  />
</template>

API Reference

Props

PropertyDescriptionTypeDefault
srcPath address of the SVG fileString''
namingCSS class name added to the injected <svg> tagString''
altAlternative text for the image (displayed on the img tag before injection)String''
optionsAdvanced configuration object passed to the svg-injector libraryObjectundefined

Events

Event NameDescriptionCallback Parameters
loadTriggered after SVG injection is complete and the DOM is replaced

Released under the MIT License.