1

This is my script that calls axios and fetch data as posts

<script>

import axios from 'axios'


export default {
  name: 'App',

  mounted: function () {
    axios.get('API URL')
      .then(response => this.posts = response.data)
  },


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


};

</script>

My code on view that tries to fetch data as posts from the script above

<template>
  <div id="app"> 
    <ul>
      <li v-for="post in posts" v-text="post.createdAt"></li>
    </ul>
  <div>
</template>

SAMPLE data fetched from API URL look like this

POSTS OBJECT VARIABLES

I am able to fetch API DATA in console log as an array but when I call one object from array which is createdAT, v-text = "post.createdAt" does not print/fetch list of createdAt date list.

1
  • There is no reason this wouldn't work, something else must be wrong. jsfiddle.net/sh0ber/qjtbw7yp Commented Mar 27, 2020 at 7:35

2 Answers 2

1

Just solved it following this document USING AXIOS TO CONSUME API here is the link for that https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html .

Above code that I have posted works fine. Problem was on my API URL which was nested inside data[data[object]]. So the way I called data from that API

from this

 mounted: function () {
    axios.get('API URL')
      .then(response => this.posts = response.data)
  }

to this

 mounted: function () {
    axios.get('API URL')
      .then(response => this.posts = response.data.data)
  }
Sign up to request clarification or add additional context in comments.

Comments

0

posts isn't reactive because the default value is null, make it an empty array, or use Vue.set instead:

Array:

posts: []

Vue.set:

.then(response => Vue.set(this, 'posts', response.data))

Edit

In response to the comments below:

You must import Vue from 'vue' to resolve the Vue is not defined error.

Regarding your v-for-key needing to be unique, you need to define a unique key on v-for elements. You can just use JSON.stringify(post):

 <li v-for="post in posts" v-text="post.createdAt" :key="JSON.stringify(post)"></li>

2 Comments

When I used your suggestion , the error that i am getting now is error Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key and error 'Vue' is not defined
@sandeshphuyal I edited my answer to show why you have these problems. These are some fundamental concepts within Vue its self, so hopefully they're helpful.

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.