Yamaha32088
Yamaha32088

Reputation: 4163

VueJS v-for inside component template does not seem to be looping

It seems like VueJS is not looping inside of my component correctly. I have an array of objects that I pass to my component as a property and I want to render them inside of the component. However I don't receive any output at all.

CodePen

Example Code Below:

<div id="sentimentForm">
  <customer-sentiment :sentiment-types="sentimentTypes" sentiment-selected="neutral"></customer-sentiment>
</div>

var sentimentReasons = [
  {label: 'Happy', value: '3', Display: 'Happy', Key: 'happy'},
  {label: 'Neutral', value: '2', Display: 'Neutral', Key: 'neutral'},
  {label: 'Angry', value: '1', Display: 'Angry', Key: 'angry'}
];

Vue.component('v-select', VueSelect.VueSelect);

Vue.component('customer-sentiment', {
  props: {
    sentiment: {
      default: null
    }, 
    sentimentSelected: {
      default: null
    },
    sentimentTypes: {
      type: Array,
      default() {
        return []
      },
    }
  },
  template: `
  <div v-for="(item, index) in mutableOptions">
    <h3>{{ index }}<h3>
    <h4>{{ item.Display }}<h4>
  </div>`,
  created: function() {
    console.log(this.sentimentTypes)
    this.mutableOptions = this.sentimentTypes;
  },
  data() {
    return {
      mutableOptions: []
    }
  }  
});

var app = new Vue({
  el: '#sentimentForm',
  data: function() {
    return {
      sentiment: '',
      sentimentSelected: '',
      sentimentTypes: sentimentReasons
    }
  }
});

Upvotes: 0

Views: 2553

Answers (1)

clueless_anh
clueless_anh

Reputation: 161

The customer-sentiment component's template should have only one root element. The template is currently having multiple <div> in first level (rendered from v-for loop), so nesting the current template in a div should fix the problem.

template: `
  <div>
    <div v-for="(item, index) in mutableOptions">
      <h3>{{ index }}<h3>
      <h4>{{ item.Display }}<h4>
    </div>
  </div>`,
created: function() {
  console.log(this.sentimentTypes)
  this.mutableOptions = this.sentimentTypes;
},

Upvotes: 5

Related Questions