For example, there is a component

Vue.component('News', { props: { data: { type: Object, default: function() { return { items: [] } } } }, created() { console.log('created'); return axios.get('/news/items') .then((response) => { console.log('data fetched'); this.data = response.data.News; }) .catch(function(error) { return Promise.reject(error.status); }); }, render: function(createElement) { console.log('render'); console.log(this.data.items); } }); 

By executing this code we get:

 created render undefined //console.log(this.data.items); data fetched render (6) [{…}, {…}, {…}, {…}, {…}, {…}, __ob__: io] //console.log(this.data.items); 

Render worked twice, the first time without waiting for data from the ajax request. So actually how to make it work only after receiving these same data? Those. to become so:

 created data fetched render 

    2 answers 2

    Because This component is better to transfer all data to the component inside.

    props: {}

    but not

    data () {}

    created (), mounted () and others - will call all methods that are tied to the "life cycle" of the instance -> component when it is changed, monitored, etc., and described in its "body".

    therefore, better use

    computed: {}

    Example:

     Vue.component('News', { data() { return { items: [] } }, computed: { getNews(){ return axios.get('/news/items') .then((response) => { return response.data.News.items; }) .catch(function(error) { return Promise.reject(error.status); }); } }, render: function(createElement) { console.log('render'); } 

    });

    And in the inside of the body of the desired tag we make

    <div v-for="(item, index) in getNews"> {{ item }}</div>

    • Thank. The idea is clear. Only the template I create using createElement (). It turns out I need to pull the getNews function in the render () itself? - Guest
    • Corrected a question on the basis of your answer. All the same, render works before the server returns data. Therefore render render two times. I don’t understand how to assign data as a result of an ajax request before the render starts ... - Guest

    In the console, this is the procedure, since the component is rendered earlier than the asynchronous data request is allowed. The first time before the arrival of the data, the render occurs because the request is asynchronous, therefore the code does not wait and is executed further. After the promise is resolved, you change the reactive data and the component is rendered again. If you want to get data when loading a component, it is better to use the mounted hook, leaving some preloader, if you want to display the component immediately with the data, then it is better to send them to the component synchronously via the component's component.