Nirman
Nirman

Reputation: 103

Passing data to dynamic component from parent component in Vue.js

I want to set data of dynamic component from the parent component

For example : Parent Component :

<div id="app">
  <template v-for="(component, index) in components">
      <component :is="component" :key="index"></component>
  </template>
  <button @click="add()">Add Component</button>
</div>

Dynamic Component :

 let dynamicComponent = {
  template: `
    <p>Welcome {{ msg }}!</p>
  `,
  data () {
    return {
      msg: 'home'
    }
  },
}

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

  data: {
    components: [
      dynamicComponent
    ]
  },

  methods: {
    add () {
      this.components.push(dynamicComponent);
    },
  }
});

I want to set the data of the dynamic component from the parent component when the new dynamic component is added.

In this case, the msg property of dynamicComponent from the parent component

Upvotes: 1

Views: 1180

Answers (2)

digout
digout

Reputation: 4252

It seems you could do this:

Parent template:

<div id="app">
  <template v-for="(component, index) in components">
      // Add :msg to pass 'msg' to child component.
      <component :is="component" :key="index" :msg="msg"></component>
  </template>
  <button @click="add()">Add Component</button>
</div>

Js:

let dynamicComponent = {
   props: ['msg'], //<-- Specify the child will receive a prop 'msg'
   template: `<p>Welcome {{ msg }}!</p>`
}

const App = new Vue({
   el: '#app',
   data: {
      components: [
         dynamicComponent
      ],
      msg: 'Hello' //<-- Set the value of 'msg'
   },

   methods: {
      add() {
         this.components.push(dynamicComponent);
      },
   }
});

Codepen

Upvotes: 1

Niklesh Raut
Niklesh Raut

Reputation: 34924

You have to use something like props:['msg'] in component

let dynamicComponent = {
  template: `
    <p>Welcome {{ msg2 }}, {{ msg }}!</p>
  `,
  props:['msg'],
  data () {
    return {
      msg2: 'component message'
    }
  },
}

const App = new Vue({
  el: '#app',
  data: {
    components: [
      dynamicComponent
    ],
    parentMsg:'parent message'
  },

  methods: {
    add () {
      this.components.push(dynamicComponent);
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
  <template v-for="(component, index) in components">
      <component :msg="parentMsg" :is="component" :key="index"></component>
  </template>
  <button @click="add()">Add Component</button>
  <input type="text" v-model="parentMsg">
</div>

Upvotes: 1

Related Questions