简体   繁体   English

添加vue组件动态

[英]Add vue component dynamic

I have a custom vue component and a view in my php-application that render a custom element for it.我在我的 php 应用程序中有一个自定义 vue 组件和一个视图,它为它呈现一个自定义元素。

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

After a ready event I add component to a main vue instance like this:ready事件之后,我将组件添加到主 vue 实例,如下所示:

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

So, I have an array of components but all of them have already rendered on a page.所以,我有一组组件,但它们都已经呈现在页面上。

The question is how can I add another article-component to the page?问题是如何向页面添加另一个文章组件?

I think that I could use a component without template and just push data to a main application when it ready but it looks a little bit weird for me.我认为我可以使用没有模板的组件,并在主应用程序准备好时将数据推送到主应用程序,但对我来说这看起来有点奇怪。 So, I think maybe there is a better solution.所以,我想也许有更好的解决方案。

You need to use Vue to do the for-loop, not your server template language:您需要使用 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>

Then anytime the articles array gets pushed to, a new article will appear.然后每当articles数组被推送到时,就会出现一篇新文章。

To initially add the articles to the page, you should do something like this (pseudo code because I don't know that template language):要将文章最初添加到页面,您应该执行以下操作(伪代码,因为我不知道该模板语言):

data:function(){

  return {

    articles: {% json_encode(articles) %}

  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM