0

I have a component that accepts props

<BarChart 
  header="header name"
  dataPoint="data_to_look_at"
  size=35
/>

With the dataPoint prop I want to use this in my component so that I can use it (I think, idk if this is the right solution) in an interpolated string like this to access items in an object

// inside of a v-for loop that iterates over an object etc
{{ data[index].attributes.${dataPoint} }}

I'm not sure how to do this and of course the above doesn't work

string interpolation Vue js

Not relevant to my question

How can I solve "Interpolation inside attributes has been removed. Use v-bind or the colon shorthand"? Vue.js 2

Not quite it either

How do interpolate a prop in a interpolation?

kawnah
  • 3,204
  • 8
  • 53
  • 103

1 Answers1

1

Observation : As you are iterating your item list by using v-for loop, No need to access the item by index. You can simply do like this :

<p v-for="data in items" :key="data.id">
    {{ data.attributes[datapoint] }}
</p>

Live Demo :

Vue.component('child', {
    data: function() {
    return {
        items: [{
        id: 1,
        attributes: {
            name: 'Alpha'
        }
      }, {
        id: 2,
        attributes: {
            name: 'Beta'
        }
      }, {
        id: 3,
        attributes: {
            name: 'Gamma'
        }
      }]
    }
  },
  props: ['header', 'datapoint'],
  template: `<div>
    <p v-for="data in items" :key="data.id">{{ data.attributes[datapoint] }}</p>
  </div>`
});

var app = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <child header="Header Name" dataPoint="name"></child>
</div>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • gotcha, can you explain the terminology of the solution, specifically `{{ data.attributes[datapoint] }}` ? – kawnah Jun 28 '22 at 17:44
  • Its simple, As you are iterating via `v-for` .. data will be consider as a item of the array and then we are trying to access `name` property (coming from the `datapoint` prop) from the `attributes` object. – Debug Diva Jun 28 '22 at 17:46