Horai Nuri
Horai Nuri

Reputation: 5578

How can I call vue.js variable in a svg fill attribute?

I retrieve datas from my backend and use it for my frontend with vue.js, for this case I'd like to change an SVG fill attribute with a vue variable.

The problem is that it doesn't work and shows as (on source code) :

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

What am I doing wrong ?

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: ["[%","%]"]
});

What am I doing wrong, How can I show my color in the svg attribute ?

Upvotes: 3

Views: 7864

Answers (2)

Bert
Bert

Reputation: 82449

Do not use interpolation in attributes. Use the binding syntax.

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

Or the shortcut

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

Upvotes: 8

rabbitwerks
rabbitwerks

Reputation: 355

I used the suggested approach and also added conditional logic to set the color dynamically from inside the method.

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

working with SVGs in Vue has proven to be tricky so best of luck! :)

Upvotes: 0

Related Questions