I am facing an issue with dynamically binding the fill attribute of an SVG rect element in VueJS. To illustrate this problem, here is a simple VueJS component that I have created (also accessible on codepen)
<template>
<div>
<!-- this example works with hardcoded id and fill attributes -->
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">
<linearGradient id="gradient1">
<stop stop-color="red" offset="0%" />
<stop stop-color="blue" offset="100%" />
</linearGradient>
<rect width="100" height="50" fill="url(#gradient1)" />
</svg>
<!-- this example does not work as expected -->
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">
<linearGradient :id="myid">
<stop stop-color="red" offset="0%" />
<stop stop-color="blue" offset="100%" />
</linearGradient>
<rect width="100" height="50" :fill="myfill" />
</svg>
</div>
</template>
<script>
new Vue({
el: 'body',
data: {
title: 'Vuejs SVG binding example',
myid: 'gradient2',
myfill: 'url(#gradient2)'
},
});
</script>
It is important to note that the fill attribute uses url() which requires the element id as an argument, making the problem more complex. The only way to reference a linearGradient defined in the same component for the fill attribute is through the id attribute of the element.
I am attempting to avoid hardcoding ids inside components because multiple instances of this component will be present on the webpage, resulting in multiple elements sharing the same id value, which is not desired.