添加vue组件dymanic

时间:2016-02-23 12:48:23

标签: javascript vue.js

我有一个自定义vue组件和我的php应用程序中的一个视图,它为它呈现一个自定义元素。

<div class="articles">
    {% for a in articles %}
    <budget-article id="{{ a.id }}" name="{{ a.name }}" :amount="{{ a.amount }}" :enable="true"></budget-article>
    {% endfor %}
</div>

ready事件之后,我将组件添加到主vue实例中,如下所示:

ready: function () {
    this.$parent.articles.push(this);
}

所以,我有一个组件数组,但所有组件都已在页面上呈现。

问题是如何在页面中添加另一篇文章组件?

我认为我可以使用没有模板的组件,只是在准备好时将数据推送到主应用程序,但对我来说看起来有点奇怪。所以,我想也许有更好的解决方案。

1 个答案:

答案 0 :(得分:1)

您需要使用Vue来执行for循环,而不是服务器模板语言:

<div class="articles">
    <budget-article v-for="article in articles" id="{{ article.id }}" name="{{ article.name }}" :amount="{{ article.amount }}" :enable="true"></budget-article>
</div>

然后,只要推送articles数组,就会出现一篇新文章。

要最初将文章添加到页面中,您应该执行以下操作(伪代码,因为我不知道该模板语言):

data:function(){

  return {

    articles: {% json_encode(articles) %}

  }

}