1

So I have created this test codepen that allows me to add components on the fly to an already existing page, but the problem here is that I don't know how to pass props to them. I've seen another question, asking something similar, where they were using a dynamic view switching across multiple components. But all of that is already done before the page itself is rendered.

With the click of a button I want to be able to dynamically create a component by name, ex:

  • <button-counter :input="'TestText'"></button-counter>
  • <vue-header :input="'TestText'"></vue-header>

What currently works is just creating the component dynamically, but without props. So placing something like button-counter or vue-header will be able to create the component (This goes for any component for that matter).

Shib
  • 296
  • 1
  • 13

1 Answers1

2

I made a few minor modifications to your Codepen on my fork here. You were very close!

The big difference is the implementation of children and how we render a dynamic component.

Original

const App = new Vue({
  el: '#app',

  data: {
    componentName: "componentName",
    input: "input",
    children: [
      buttonCounter,
      vueHeader
    ]
  },

  methods: {
    add () {
      this.children.push(this.componentName)
    },
  }
});

Modified

const App = new Vue({
  el: '#app',

  data: {
    componentName: "componentName",
    input: "input",
    children: [
      { componentName: 'button-counter', input: 'I am a button' },
      { componentName: 'vue-header', input: 'I am a header' }
    ]
  },

  methods: {
    add () {
      this.children.push({ 
        componentName: this.componentName, 
        input: this.input 
      })
    },
  }
});

Likewise, your v-for changes on your template as well to accommodate the new shape of the children array:

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

So, as you can see, by making your children an object array which can then accept any props, you can pass those same props into the dynamic component. In this case, we have a prop called input for both of your custom components which are defined as part of this object array.

One thing to note is that, for Dynamic Components in Vue.js, the is prop can either accept the component itself (e.g. your original approach) or a string representation of an already registered component. That part there is the main differentiator between your original and my fork.

hth!

grales
  • 306
  • 2
  • 10