将数据从Vue.js中的父组件传递到动态组件

时间:2020-01-08 07:14:25

标签: vue.js vuex

我想从父组件设置动态组件的数据

例如: 父组件:

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

动态组件:

 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);
    },
  }
});

我想在添加新的动态组件时从父组件设置动态组件的数据。

在这种情况下,父组件中dynamicComponent的 msg 属性

2 个答案:

答案 0 :(得分:1)

您必须在组件

中使用props:['msg']之类的东西

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>

答案 1 :(得分:1)

看来您可以这样做:

父模板:

<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