1

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

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.