0

I have a custom vue component and a view in my php-application that render a custom element for it.

<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: 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.

1 Answer 1

1

You need to use Vue to do the for-loop, not your server template language:

<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.

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) %}

  }

}
Sign up to request clarification or add additional context in comments.

5 Comments

In other words you suggest to push articles from server to Vue instance. By ajax request, dumping json on the page and so on.
Yes. Vue manages the DOM for you, all you have to do is get it the data. Ideally you do zero DOM manipulation yourself and simply have it react to data changes. You can get that data via ajax or dumping json like you said!
Actually this is exactly what I would like to avoid. My javascript is in a separate file and I do not like the idea of using global variable to fill its article's list of passing an url to fetch the articles. I think that I could combine my workflow with yours. I'll render my budget-article component on a page but I'll add a v-for loop for articles that newly created on this page.
I guess if your JS is in a separate file you would not be able to use the templating engine so you'd need to use a separate http request to fetch the articles. If you really want to avoid that then your way sounds like a good option.
I render several budget-article elements and when js runs it converts them into a normal html according template. So the main idea is to render components on the page before Vue starts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.