0

I am looping through an array of colors in vue to display color codes and also the name of the color within a tooltip. The tooltip uses data attributes via html 5.

Now I am trying to bind this via vue and the only syntax I can think of and which is used in all vue documentation is this

<div 
  :data-tooltip="color.name"
  v-for="(color, index) in colors"
  :key="index"    
  @click="setColor(color)"
  class="color-box"
  :style="{ background: color.hexCode}"></div>

However, this won't work and results in the DOM like this:

<div
  data-v-d0a245c6=""    
  class="color-box"
  style="background: rgb(0, 247, 0);"></div>

I would expect it to look like this:

<div
  data-attribute="Sunny yellow"
  class="color-box"
  style="background: rgb(0, 247, 0);"></div>

But for some reason, I cannot dynamically bind an attribute which uses dashes.

I also tried camel casing:

<div
  :dataTooltip="color.name"
  v-for="(color, index) in colors"
  :key="index"
  @click="setColor(color)"
  class="color-box"
  :style="{ background: color.hexCode}"></div>

with the same result; what am I doing wrong here?

1 Answer 1

2

You could use v-bind:

<div v-bind="getDataAttr(color.name)" v-for="(color, index) in colors" :key="index" @click="setColor(color)" class="color-box" :style="{ background: color.hexCode}">

...

methods: {
  getDataAttr(color) {
    return {
      'data-tooltip': color
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

So, this one will basically replace v-bind="getDataAttr(color.name)" by data-tooltip="red" ? Wow ! :D
Yes exactly - and you can return any number of data- attributes from the getDataAttr method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.