从数组动态渲染多个组件

时间:2018-05-15 07:28:48

标签: vue.js

我正在尝试在名为ChildTabs的子组件中动态呈现组件。我想基于从名为Contatcs的父视图传递到组件的数组来呈现组件。

例如,如果我从名为“Big”的contact_type传递form_type,它将在我的选项卡vue上呈现。但是我有其他数据包含我试图渲染的多个组件,例如包含多种形式的介质,例如Red Green&蓝色。

我有一个想法是使用prop数据form_type在我的方法中创建一个for循环,所以我可以检索我想要调用的表单列表,但那是我不知道下一步该做什么的地方。我已经导入了表单,我不知道如何渲染它们。

欢迎任何建议。

Contacts.vue

<template>
    <div class="row">
          <ChildTabs
                :form_type="contact_types"
            />
    </div>
</template>


<script>
  'use strict';

  import ChildTabs from '../tabs';

  export default {
    name: 'contacts-view',
    data: function () {
        return {
            form_data: {},
            failed_validations: [],
            contact_type: '',
            contact_types: [
                {
                    label: 'Big',
                    value: 'big',
                    form_type: [
                        'Red'
                    ]
                },
                {
                    label: 'Medium',
                    value: 'medium',
                    form_type: [
                        'Red',
                        'Green',
                        'Blue'
                    ]
                },
                {
                    label: 'Small',
                    value: 'small',
                    form_type: [
                        'Blue',
                        'Green'
                    ]
                },
            ],
        }
    },

    props: {

    },

    computed: {

    },

    methods: {
    },

    components: {
        ChildTabs
    }
}
</script>

Tabs.vue

<template>
  <!--=============================================================-->
  <!-- Contact Forms -->
  <!--=============================================================-->
</template>

<script>
  'use strict';

  import Red from './forms/red';
  import Green from './forms/green';
  import Blue  from './forms/blue';

  export default {
    name: 'forms-tab',

    data: function () {
        return {
        }
    },

    props: {
        form_type: {
            type: Array,
            required: false,
            default: []
        },
    },

    computed: {

    },

    methods: {
        RenderComponent: function ()
        {
            this.$props.form_type
        }
    },

    created: function () {
      this.RenderComponent();
    },

    components: {
      Red,
      Blue,
      Green
    }
  }
</script>

1 个答案:

答案 0 :(得分:1)

您可以在Vue中使用dynamic component

<template>
  <div>
    <div v-for="type in form_type" :key="type">
      <component :is="getCompentName(type)"/>
    </div>

  </div>
</template>

<script>
  export default {
    ...
    methods: {
      getCompentName(type) {
        switch (type) {
          case 'red':
            return 'red'
          case 'blue':
            return 'blue'
          case 'green':
            return 'green'
          default:
            return 'red'
        }
      }
    }
  }
</script>
相关问题