N
N
Natalya Chobot2017-07-08 16:36:53
Vue.js
Natalya Chobot, 2017-07-08 16:36:53

How to dynamically create tags in HTML using Vue.js?

There is such a function in js.js:

function viewPosts(){
    $.getJSON("http://localhost:3000/posts", function (obj) {
        $.each(obj, function (key, value) {
            var app = new Vue({
                el: '#app',
                data: {
                    title: value.title,
                    subtitle: value.subtitle,
                    date: value.datePostCreate,
                    text: value.text
                }
            });
    });
});

Here is what is in index.html:
<div id="app">
                <p>{{ title }}</p>
                <p>{{ subtitle }}</p>
                <p>{{ date }}</p>
                <p>{{ text }}</p>
            </div>

How can I make it so that each new post has its own markup?
It is possible that both js.js and index.html need to be fixed. I just got acquainted with Vue.js, I don’t know all the features.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem0071, 2017-07-08
@nata-ponchik

You do it a little

var app = new Vue({
                el: '#app',
                data: {
                    title: value.title,
                    subtitle: value.subtitle,
                    date: value.datePostCreate,
                    text: value.text
                }
            });

This piece initializes your Vue. So you don't need to run it multiple times.
Here's a skeleton for your application
<div id="app">
               
</div>
var app = new Vue({
                el: '#app'
            });

Going further
In the view, create a mounted() method - it is initialized on load
mounted(){
 // ....
}

Here is where // .... and write your code
. And in order for the blocks to repeat, there is a special v-for method.
As a result, I suppose you should get something like this:
<div id="app">
  <div v-for="item in items">
     <p>{{ item.title }}</p>
     <p>{{ item.subtitle }}</p>
     <p>{{ item.date }}</p>
     <p>{{ item.text }}</p>
  </div>
</div>

var app = new Vue({
                el: '#app',
                data: {
                    items: [];            //здесь будет массив с вашими данными
                },
                mounted(){
                     this.$http.get("http://localhost:3000/posts")          // это использует vue-router. можно и по другому, но как по мне это самый удобный способ
                                   .then(res => {
                                        this.items = res.body         // здесь заносим ваши данные в массив
                                   })
            });

Basically, this is how it should look like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question