Home > OS >  Why I cannot render AJAX JSON value?
Why I cannot render AJAX JSON value?

Time:06-14

Here is my code:

<ul>
  <li v-for="value in RandomTopic" :key="value.id">{{ value.title }}</li>
</ul>
export default {
  data() {
    return {
      RandomTopic: null
    }
  },
  mounted() {
     ///some method to get data from remote server
     console.log(res.data);
     this.RandomTopic = res.data;
  }
}

I want to render all the data from the remote server in front end. However, after the program ran, it reports this error:

Cannot set property 'RandomTopic' of undefined ; at api request success callback function
TypeError: Cannot set property 'RandomTopic' of undefined

The console.log(res.data); log the JSON successfully so it seems not the problem of AJAX or remote server.

And also, here is a sample of the JSON:

[
    {
        "id": 421,
        "title": "sample1",
        "image_url": "bus.png"
    },
    {
        "id": 535,
        "title": "sample78",
        "image_url": "car.png"
    }
]

What's wrong with my code ? I am a beginner of Vue 3, please help me.

CodePudding user response:

You can try with axios or with native fetch:

const app = Vue.createApp({
  data() {
    return {
      RandomTopic: null
    }
  },
  mounted() {
    axios.get('https://jsonplaceholder.typicode.com/todos')
      .then((res) => this.RandomTopic = res.data)
 /* fetch('https://jsonplaceholder.typicode.com/todos')
      .then(response => response.json())
      .then(json => this.RandomTopic = json) */
  }
})
app.mount('#demo')
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <ul>
    <li v-for="value in RandomTopic" :key="value.id">{{ value.title }}</li>
  </ul>
</div>

CodePudding user response:

As per the error you mentioned, Issue is basically related to the scope of this. Looks like you are using regular function instead of arrow function ( => {...}) which don't provide their own this binding (it retains this value of the enclosing lexical context).

Reference - Arrow function

.then(res => {
    this.RandomTopic = res.data;
})
  • Related