javascript - 是否可以在 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
值的元素,这是不应该发生的。
解决方案
是的,可以做想做的事。我做了一些类似的事情,但只有一个 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>
推荐阅读
- node.js - 如何使用 MongoDB 显示由“NAME”创建的
- linux - 如何在 shell 中遍历我的文本文档中的单词。我想在我的文本文档中显示字数
- react-admin - 如何在 AppBar 上设置配置显示/隐藏刷新按钮
- sql-server - MariaDB 和 Microsoft SQL Server 在同一台服务器上
- angular - Angular 6无限滚动(滚动)不起作用
- javascript - 从字面上看,画布另存为png
- ios - Swift 中的日志行号和方法名
- apache-spark - Spark Dataframe 复杂排序
- node.js - Reactjs 网络热敏打印机
- java - 在给定数组中查找键数组(一个模式)