Is there a way to reference a vue.js variable within a SVG fill attribute?

When fetching data from my backend to use in my frontend with vue.js, I encountered an issue where I wanted to change an SVG fill attribute using a vue variable.

The problem arises when it displays (in the source code) like this:

<rect width="500" class="color color-1" height="500" fill="[% colorAttr() %]"></rect>

instead of:

<rect width="500" class="color color-1" height="500" fill="#fafafa"></rect>

Can anyone point out what mistake I might be making?

Fiddle : https://jsfiddle.net/cy5gevLy/

HTML :

<div id="colorHandler">
  <p>[% colorAttr() %]</p>
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 856.2987727011634 500" enable-background="new 0 0 500 500" xml:space="preserve">
    <g id="c" transform="translate(0, 0) scale(1.736, 1)">
      <g>
        <rect width="500" class="color color-1" height="500" fill="[% colorAttr() %]"></rect>
      </g>
    </g>
  </svg>
</div>

JavaScript :

var color = new Vue({
  el: '#colorHandler', 
  methods:{
    colorAttr:function(){
        var my_color = '#fafafa';
        return my_color
    }
  },
  delimiters: ["[%","%]"]
});

Any suggestions on how I can correctly display my chosen color in the svg attribute?

Answer №1

Avoid using interpolation within attributes and instead utilize the binding syntax.

<rect width="500" class="color color-1" height="500" v-bind:fill="colorAttr()"></rect>

Alternatively, you can use the shortcut:

<rect width="500" class="color color-1" height="500" :fill="colorAttr()"></rect>

Answer №2

Utilizing the recommended method, I incorporated conditional logic to dynamically set the color within the function.

methods: {
  setAsActiveColor () {
  const activeColor = '#eeeeee';
  const inactiveColor = '#0a0a0a';
  if (this.toggleMoreOptions.moreOptionsToggled) return activeColor;
  return inactiveColor;
  }
}

Navigating SVGs in Vue has presented its challenges, but wishing you the best of luck! :)

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

Can someone explain the meaning of the paragraph in the "Index Routes" section of the React-Router documentation?

Lesson 8 of the React-Router tutorial delves into the concept of "Index Routes", outlining the importance of structuring routes in a specific way. Here are some key points from their discussion: The tutorial suggests that while setting up the initial rout ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

Steps for correctly displaying a success message after clicking and copying to the clipboard:

In the process of developing a color palette, I am incorporating a clipboard icon enclosed in a Tooltip component alongside each color. The functionality involves copying the color's name to the user's clipboard upon clicking the icon. Subsequent ...

Utilizing JavaScript for the removal or hiding of span elements with specific class attributes

I am currently working on a software project that involves compiling HTML fragments and then exporting them to Microsoft Word. My goal is to create a script that will cycle through these compiled fragments and remove specific tags that have a particular CS ...

Service workers do not support fetching from .html files

Struggling with creating a functioning service worker for offline use has been a challenge. Despite trying numerous examples, the success has remained elusive. Initially, I suspected that the dynamic nature of my PHP-based website was causing the issue, or ...

Parsing error: Unexpected character found at line 238, column 16. Consider using a loader suitable for this file format

Currently, I am attempting to integrate ArcballControls.js controls into my Vue.js application. I've noticed that this particular class contains functions that utilize arrow syntax, whereas every other class in the controls does not. This seems to be ...

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here. ...

Refreshing the page causes the Angular/Ionic Singleton instance to be destroyed

I have a TypeScript singleton class that is responsible for storing the login credentials of a user. When I set these credentials on the login page and navigate to the next page using Angular Router.navigate (without passing any parameters), everything wor ...

Which is more efficient: filtering a JSON object or querying the database using ajax?

I am currently developing a product page that involves a selection of options that will impact the pricing of the items. The primary option allows users to choose a material, which then influences the available set of options. Within the database, there i ...

Pagination - crafting a fresh page

Seeking advice on the best practice for client-side handling of pagination in a question/answer thread, similar to Stack Overflow. The data structure includes upvote/downvote comments and looks like this: data: (10) [{…}, {…}, {…}, {…}, {…}, { ...

Is it possible to utilize optgroup multiple times within a select tag in a vuejs template within a Laravel project?

In my Laravel project, I am implementing Vue.js. I have a select tag in my project that contains two optgroup tags. However, within the Vue.js template, only the label of the first optgroup tag is being displayed, and the label of the second optgroup tag o ...

Exploring the power of AngularJS by nesting elements within multidimensional arrays and revealing their content through a simple

Check out this fiddle for accurate information, though it may not be visually positioned correctly: http://jsfiddle.net/LhRfq/ I am working with a three-dimensional JSON object. The first level of array items should be displayed in a single line, which ...

What steps can I take to address security issues related to iframes?

Are there other security risks to consider when using iframes besides XSS vulnerabilities? How can I ensure that my website is secure when utilizing iframes? I've seen some JavaScript code that uses top.window, but I'm hesitant to rely on client ...

(angular 8) Error occurred when converting a file or image to FormData due to an invalid value (Note: FormData object printed as Object Form{})

I encountered an issue where I am getting an invalid value from form data. The value appears correct in `this.fileData` with a size of 5701, but becomes empty when converted to form data - `{}` is logged when I console.log the form data. Additionally, acce ...

Oops! Looks like we're missing some vital information (Could the User input object from angular not be reaching node?). Both data and

Exploring the world of MEAN stack with basic applications and tutorials has been my recent endeavor. Currently, I am working on capturing user input from a registration form using Angular and encrypting passwords using bcrypt. Interestingly, despite loggin ...

Arrangement of 3 points on the graphical user interface

Seeking the orientation of 3 ordered points in space using an algorithm discovered on this site: https://www.geeksforgeeks.org/orientation-3-ordered-points/ Desiring to display the orientation on GUI as Clockwise or CounterClockwise while adjusting coordi ...

Utilizing PHP for a server-side backup in case the CDN is inaccessible

Looking to simulate some server-side functionality: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> if (typeof jQuery == 'undefined&apo ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...