首页 > 解决方案 > VueJS v-for inside 组件模板似乎没有循环

问题描述

看起来 VueJS 没有在我的组件内正确循环。我有一个对象数组,我将它们作为属性传递给我的组件,并且我想在组件内部呈现它们。但是我根本没有收到任何输出。

代码笔

下面的示例代码:

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

标签: javascriptvue.jsvuejs2

解决方案


组件的customer-sentiment模板应该只有一个根元素。该模板当前<div>在第一级有多个(从循环渲染v-for),因此将当前模板嵌套在 a 中div应该可以解决问题。

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

推荐阅读