添加 vue 组件动态

Add vue component dynamic

本文关键字:动态 组件 vue 添加      更新时间:2023-09-26

我有一个自定义的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);
}

因此,我有一个组件数组,但所有这些组件都已经呈现在页面上。

问题是如何向页面添加另一个文章组件?

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

你需要使用 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) %}
  }
}