【问题标题】:Passing data to dynamic component from parent component in Vue.js在 Vue.js 中从父组件向动态组件传递数据
【发布时间】:2020-01-08 07:14:25
【问题描述】:

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

例如: 父组件:

<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属性

【问题讨论】:

    标签: vue.js vuex


    【解决方案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>

    【讨论】:

      【解决方案2】:

      看来你可以这样做:

      父模板:

      <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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-31
        • 2017-01-05
        • 2017-06-10
        • 2018-08-15
        • 1970-01-01
        • 2016-12-13
        • 2021-04-22
        • 2018-02-13
        相关资源
        最近更新 更多