首页 > 解决方案 > 是否可以在 VueJS 中绑定使用 url() 的 SVG 填充属性?

问题描述

我需要动态绑定 SVG rect 元素的填充属性,但它不起作用。这是我的简单 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>

请注意,使用元素 id 作为参数的fill属性使事情复杂化。url()据我所知,在同一组件中定义的fill属性使用的唯一方法linearGradient是通过元素id属性引用它。

我试图这样做的原因是因为我想避免id在组件内部进行硬编码。由于我将在网页上有许多此组件的实例,因此会有多个具有相同id值的元素,这是不应该发生的。

标签: javascripthtmlcssvue.jssvg

解决方案


是的,可以做想做的事。我做了一些类似的事情,但只有一个 div 而不是 svg。

理论

将动态 css 类名绑定到 svg 并将填充物放入该类中。此链接显示如何使用 css 获取 css CSS - Style svg fill with class name

我提出的解决方案假设通过 props 将一些值传递给组件

解决方案

<template>
...

    <rect width="100" height="50" :class="myfill" />
...
</template>

<script>
new Vue({
  el: 'body',
  data: {
    title: 'Vuejs SVG binding example',
    myid: 'gradient2',
    myfill: somePropYouPassedIn
  },
});
</script>

修改为第一个答案

在尝试你的小提琴时,我认为你的编码是正确的,你只是在使用旧版本的 Vuejs(当我试图让你的小提琴工作时,我注意到了这一点)。无论如何,我无法让你的笔与 vue 一起使用,所以我在这里创建了一个全新的小提琴https://jsfiddle.net/nkalait/ohmzxb7L/

代码

<div>
  {{ title }}
  <!-- 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">
    <rect width="100" height="50" :fill="gradient1" />
  </svg>

  <!-- this doesn't work... -->
  <svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <rect width="100" height="50" :fill="gradient2" />
  </svg>


  // I HAVE PUT THE GRADIENTS IN THERE OWN SVG
  <svg aria-hidden="true" focusable="false" style="width:0;height:0;position:absolute;">
    <linearGradient id="gradient1">
      <stop stop-color="yellow" offset="0%" />
      <stop stop-color="blue" offset="100%" />
    </linearGradient>
    <linearGradient id="gradient2">
        <stop stop-color="red" offset="0%" />
        <stop stop-color="green" offset="100%" />
    </linearGradient>
  </svg>
</div>

推荐阅读