Patrick
Patrick

Reputation: 374

How to display array data?

I want what is in the colors array (hex codes for now) to display in the template <color-block> that I have created.

Vue.component('color-block', {
    props: ['hexcolor'],
    template:
    `
    <div class="col-lg-1 col-md-4 col-sm-6 col-xs-12"
    	{{ colors.hex }}
    </div>
    `
});
new Vue({
    el: '#app',
    data: {
    	colors: [
        { color: 'Red', hex: '#FF0000' },
        { color: 'Blue', hex: '#0000FF' }
        ]
    }
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
    <color-block v-for="hex in colors" :colorBlock="hex">
    </color-block>
</div>

https://jsfiddle.net/eywraw8t/168833/

Upvotes: 0

Views: 57

Answers (1)

tony19
tony19

Reputation: 138196

A few problems:

  • Your demo sets :colorBlock="...", but the prop is actually named hexcolor in the component, so the setting should be :hexcolor="..."
  • In the v-for loop, hex is an object ({color: 'Red', hex: '#FF0000'}), but I assume you only wanted to pass the hex color code, so the setting should be :hexcolor="hex.hex".
  • Your color-block template is missing a closing bracket after the class
  • Your color-block template references colors.hex, but colors is not part of the component (it's part of app's data). You probably meant to display the value of the component's prop (hexcolor).

Demo with corrections made:

Vue.component('color-block', {
  props: ['hexcolor'],
  template: `
    <div class="col-lg-1 col-md-4 col-sm-6 col-xs-12">
      {{ hexcolor }}
    </div>
    `
});

new Vue({
  el: '#app',
  data() {
    return {
      colors: [
        { color: 'Red', hex: '#FF0000' },
        { color: 'Blue', hex: '#0000FF' }
      ]
    };
  }
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
  <color-block v-for="hex in colors" :hexcolor="hex.hex">
  </color-block>
</div>

Upvotes: 1

Related Questions