【问题标题】:How to create a vue component dynamically如何动态创建vue组件
【发布时间】:2015-11-10 21:38:30
【问题描述】:

我在我的 vue 实例中创建了一个组件。

components: {
        plan: {
            template: "#suggested-properties",
            props: ['plan', 'active'],
            computed: {
                isActive: function(){
                    return this.plan.name == this.active.name;
                }
            },
            methods: {
                setActivePlan: function(){
                    var that = this;
                    that.activeParameter= true;
                    this.active = this.plan;
                }
            }
        }
    }

有没有一种方法可以在我单击按钮时通过传递数据来动态创建相同组件的实例?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    希望我能正确理解您的问题,您只需要遍历一个数组即可。

    data: {
      numOfComps: 0
    }
    

    在您的 HTML 中:

    <component v-for="comp in numOfComps></component>
    

    检查小提琴以获取工作示例:

    http://jsfiddle.net/gc2t8o5t/

    【讨论】:

    • 你知道有什么方法可以将 :prop JSON 对象传递给这样创建的组件吗?
    • @kyeno 您可以像在任何其他组件中一样添加道具
    【解决方案2】:

    如果您事先不知道组件的名称,这里是一个解决方案

    <component v-for="comp in arrayOfCompsString" :is="comp"></component>
    

    会正确替换整个标记

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 2020-02-22
      • 1970-01-01
      • 2019-07-12
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      相关资源
      最近更新 更多