【发布时间】:2020-03-15 00:04:14
【问题描述】:
我需要动态绑定 SVG 矩形元素的填充属性,但它不起作用。这是我的简单 VueJS 组件,用于演示我正在尝试做的事情(也可以在 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>
请注意fill 属性使用url(),它将元素ID 作为参数,这使事情变得复杂。据我所知,fill 属性使用同一组件中定义的linearGradient 的唯一方法是通过元素id 属性引用它。
我之所以尝试这样做是因为我想避免在组件内部硬编码ids。由于我将在网页上有许多此组件的实例,因此会有多个具有相同 id 值的元素,这是不应该发生的。
【问题讨论】:
标签: javascript html css vue.js svg