简体   繁体   中英

How to render array of component instances in vue.js?

I need to build list of dynamical components that I can group in group component. Then I need to send all information about builded components and groups.

I can use <component v-for="componentName in myComponents" :is="componentName"></component> , and get information about components using this.$children.map(component => component.getInformation()) , but then I can't move some component to group component, because I have only component name not the component instance with data (it just render with default data).

I also can use this:

<template>
  <div ref="container"> </div>
</template>

<script>
  import someComponent from 'someComponent.vue'
  import Vue from 'vue'

  export default {
    data () {
      return {
        myComponents: []
      }
    },
    methods: {
      addSomeComponent () {
        let ComponentClass = Vue.extend(someComponent);
        let instance = new ComponentClass({});
        myComponents.push(instance);
        instance.$mount();
        this.$refs.container.appendChild(instance.$el)
      },
      getInformation () {
        return this.myComponents.map(component => component.getInformation());
      }
    }
  }
</script>

But then I can't use reactivity, directives (eg directives for drag and drop), and it's not data driven pattern.

Any suggestions?

<template>
    <div class="component">
        <template v-for="(child, index) in children()">
            <component :is="child" :key="child.name"></component>
        </template>
    </div>
</template>

<script>
  import someComponent from 'someComponent.vue'
  import Vue from 'vue'

  export default {
      methods: {
        children() {
            let ComponentClass = Vue.extend(someComponent);
            let instance = new ComponentClass({});

            return [
                instance
            ];
        },
      }
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM