I'd need to dynamically bind fill attribute of a SVG rect element but it doesn't work. Here is my simple VueJS component to demonstrate what I am trying to do (also available in codepen)
<template>
<div>
<!-- this works but id and fill attributes are hardcoded -->
<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 doesn't work... -->
<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>
Notice that fill
attribute uses url()
which takes element id as argument which complicates the thing. As far as I know the only way for fill
attribute to use linearGradient
defined in the same component is to reference it by element id
attribute.
The reason I am trying to do this is because I want to avoid hardcoding id
s inside components. Since I will have many instance of this component on the webpage, there will be multiple elements with same id
value which should not happen.