Can VueJS bind the SVG fill attribute with url() when using VueJS?

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.

Answer №1

Absolutely, achieving what you desire is indeed possible. I have personally implemented something similar in the past, although it was with a div rather than an svg element.

The Concept

The key is to bind a dynamic CSS class to the svg element and define the fill within that class. This helpful guide demonstrates how to utilize CSS to style svg elements with a class name: CSS - Style svg fill with class name

My suggested approach assumes that you are passing a value to the component through props.

The Resolution

<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>

Update to Initial Response

Upon testing your fiddle, it appears that your coding logic was correct. The issue stemmed from using an outdated version of Vuejs (which became apparent during my troubleshooting efforts). Unfortunately, I was unable to make your pen work with Vue, so I created a new fiddle from scratch here: https://jsfiddle.net/nkalait/ohmzxb7L/

Code Snippet

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the quickest way to implement an instant search feature for WordPress posts?

Today, I have a new challenge to tackle on my website. I am determined to implement an INSTANT SEARCH feature that will search through all of my posts. One great example to draw inspiration from is found here: Another impressive implementation can be se ...

What is the best way to move table data content to a new line?

I have a table that spans the entire width of the screen, with 3 <td> elements inside. The content in the 2nd <td> does not contain any spaces and is quite long, causing it to expand beyond its allotted 70% width and disrupt the layout. Is ther ...

How to implement jQuery CSS hover effect using jQuery?

I've configured the hover opacity in my CSS, .button-simple:hover { opacity:.70; filter:alpha(opacity=70); filter: "alpha(opacity=70)"; } However, the hover opacity is not displaying after adding this line to my code, $('input[type ...

Here's how you can arrange a list starting with the first item and then searching for a specific string using md-autocomplete in

As a newcomer to angularJs, I am looking for ways to filter search results more efficiently. Check out this example here: https://codepen.io/anon/pen/mpJyKm I am trying to customize the search result by filtering based on query input. Specifically, I wan ...

The search engine results page (SERP) is only displaying the homepage and not any of the subpages

Check out this search to see that only my main page is indexed. Why aren't Google and other search engines picking up arda-maps.org/about/ and the other subpages? Is my deep linking technique incorrect? Do the search engines just need more time? If s ...

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

Inheritance from WebElement in WebdriverIO: A Beginner's Guide

I am seeking a solution to extend the functionality of the WebElement object returned by webdriverio, without resorting to monkey-patching and with TypeScript type support for autocompletion. Is it possible to achieve this in any way? class CustomCheckb ...

React Issue: Make sure to assign a unique "key" prop to each child element within a mapped list

I encountered the error message below: react Each child in a list should have a unique "key" prop. Here is my parent component code snippet: {data.products .slice(4, 9) .map( ({ onSale, ...

After clicking multiple times within the modal, the modal popup begins to shift towards the left side

I successfully implemented a modal popup in my project, but encountered an issue where the popup moves to the left side if clicked multiple times. Despite searching extensively online, I have not been able to find a solution to this problem. Below is the ...

The act of coming back with just one array

I'm having trouble grasping the concept of returning a single array from a function that calls another function multiple times. The issue I'm facing is that each time the scrapingfunction runs, the console.log in the code provided outputs an arra ...

Navigating through a multistep form in AngularJS using UI Router and arrow keys for seamless movement

Is there a way to navigate to the next or previous form step using arrow keys in AngularJS UI Router? The code provided below is currently allowing navigation with previous and next buttons. .config(function($stateProvider, $urlRouterProvider) { $stat ...

What is the process of encoding a String in AngularJS?

Utilizing Angularjs for sending a GET HTTP request to the server, which is then responded to by the Spring MVC framework. Below is a snippet of code depicting how the URL is built in Angular: var name = "myname"; var query= "wo?d"; var url = "/search/"+qu ...

Shifting elements within Phoria.js

I'm currently working on a game where a ball bounces and falls into a randomly placed bin. I'm wondering if there's a way for the ball to jump and land based on the dynamic coordinates of the bin. If I have knowledge of the direction and dis ...

Separating vendor and application code in Webpack for optimized bundling

Recently, I created a React+Webpack project and noticed that it takes 60 seconds to build the initial bundle, and only 1 second to append incremental changes. Surprisingly, this is without even adding my application code yet! It seems that the node_modules ...

td:before combined with vertical-align:middle

To achieve a table with square cells, I implemented the following CSS: table { width: 100%; table-layout: fixed; } td { text-align: center; vertical-align: middle; } td:before { content: ''; padding-top: 100%; float: ...

Tips on saving a cookie using universal-cookie

I followed a solution on Stack Overflow to set a cookie in my React application. However, the cookie expires with the session. Is there a way I can make this cookie persist beyond the session so it remains even when the browser is closed and reopened? ex ...

Customize the delete icon margin styles in Material-UI Chip component

Currently, I have implemented the V4 MUI Chip component with a small size and outlined variant, complete with a specified deleteIcon. However, I am encountering difficulties when attempting to override the margin-right property of the deleteIcon due to MUI ...

ajax - Text not appearing in Google's cached version

My website retrieves content using MS AJAX from an ASP.NET webservice. However, when I check the cached version on Google, I notice that the initial text is not displayed. I am wondering what would be the most effective method to ensure the website's ...

Using Angular's Hostbinding feature to toggle a button and change the background color of the

How can I change the background color of a page and all child components when a toggle button is clicked? Can this be accomplished using HostBinding in Angular? <div class="mainbody" [class.bgnight]="haveClass"> <button (click) ...

React components to separate static PDF pages

I have successfully implemented a feature in my React App that allows me to export a long page in PDF format using html2canvas and jsPDF. The code snippet for exporting the page is as follows: html2canvas(document.body).then((canvas) => { var img ...