DonMB
DonMB

Reputation: 2718

vue bind html data attribute within for loop

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?

Upvotes: 0

Views: 658

Answers (1)

Hannah
Hannah

Reputation: 1143

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

Upvotes: 2

Related Questions