【问题标题】:How to pass props / data to dynamically added components?如何将道具/数据传递给动态添加的组件?
【发布时间】:2019-05-03 18:17:50
【问题描述】:

所以我创建了这个测试codepen,它允许我将组件即时添加到已经存在的页面,但这里的问题是我不知道如何将道具传递给它们。我见过another question,问过类似的问题,他们在哪里使用跨多个组件的动态视图切换。但所有这些都在页面本身呈现之前就已经完成了。

通过单击按钮,我希望能够按名称动态创建组件,例如:

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

目前的工作是动态创建组件,但没有道具。因此,放置按钮计数器或 vue-header 之类的东西就可以创建组件(这适用于任何组件)。

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    我对您的 Codepen on my fork here 做了一些小的修改。你很亲密!

    最大的区别在于children 的实现以及我们如何渲染动态组件。

    原创

    const App = new Vue({
      el: '#app',
    
      data: {
        componentName: "componentName",
        input: "input",
        children: [
          buttonCounter,
          vueHeader
        ]
      },
    
      methods: {
        add () {
          this.children.push(this.componentName)
        },
      }
    });
    

    修改

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

    同样,您的模板上的v-for 也会发生变化,以适应children 数组的新形状:

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

    因此,如您所见,通过将 children 设为可以接受任何道具的对象数组,您可以将这些相同的道具传递给动态组件。在这种情况下,我们为您的两个自定义组件提供了一个名为 input 的属性,它们被定义为该对象数组的一部分。

    需要注意的是,对于 Vue.js 中的动态组件,is 属性可以接受组件本身(例如您的原始方法)或已注册组件的字符串表示。那部分是您的原始叉子和我的叉子之间的主要区别。

    hth!

    【讨论】:

    • 天哪,我从没想过我可以将完整的对象直接传递给这个东西。谢谢您的帮助!我一直在努力让它工作多年!
    • np,很高兴为您服务 :)
    猜你喜欢
    • 2021-04-03
    • 2021-07-08
    • 2019-01-27
    • 2017-01-07
    • 1970-01-01
    • 2018-07-17
    • 2021-12-21
    • 2019-04-24
    相关资源
    最近更新 更多