user3845661
user3845661

Reputation:

vue component doesn't show data

Axios loads data without any problem, doesn't show any data, Laravel Mix builds without error.

I have following code:

index.html (body)

<div id="app">
    <posts></posts>
</div>

In app.js I use this:

import Vue from 'vue';

// global declare axios
window.axios = require('axios');

import Posts from './components/Posts';
Vue.component('posts', Posts);

new Vue({
    el: '#app',

    props: {
        posts:[{
            userId: [Number],
            id: [Number],
            title: [String, Number]
        }]
    }
});

In the Posts.vue component I create a template and a script loading the data when mounted:

<template>
    <ul>
        <li v-for="post in posts" v-text="post.title"></li>
    </ul>
</template>

<script>
    export default {


        data: function() {
            return {
                posts: null,
            }
        },

        // when stuff is loaded (document ready)
        mounted: function() {

            // use placeholder data for tests, capture asynchronous data from site using this.
            axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => this.posts = response.posts)
                .catch(error => this.posts = [{title: 'No posts found.'}])
                .finally(console.log('Posts loading complete'));
        },
    }
</script>

So the data should be shown as a ul list:

<ul>
  <li>
     title
  </li>
  <li>
     title
  </li>
  <li>
     title
  </li>
</ul>

Upvotes: 0

Views: 927

Answers (2)

vishal
vishal

Reputation: 116

` Here "this.post" not take it has instance in axios call.So you have follow like this. `

var vm=this;

axios.get('https://jsonplaceholder.typicode.com/posts') .then(response => vm.posts = response.posts) .catch(error => vm.posts = [{title: 'No posts found.'}]) .finally(console.log('Posts loading complete'));

Upvotes: 0

Rich
Rich

Reputation: 562

Try the code below, I've made comments on the bits that need changing.

data() {
    return {
        posts: [] // this should be an array not null
    };
},

// you can do this on created instead of mounted
created() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            this.posts = response.data; // add data to the response
        });

Upvotes: 2

Related Questions