Error fetching data from axios in vuejs app [duplicate]

问题: This question already has an answer here: How to access the correct `this` inside a callback? 10 answers Hey I am trying to make a full stack app w...

问题:

This question already has an answer here:

Hey I am trying to make a full stack app with vuejs fastifyjs(node framework). The vue app gets data from the api I developed and also display it in the browser console but it does not render it in the app. I even tried to load it on mount function but nothing happens.

Here is the complete code I am using.

const app = new Vue({
  el:'#app',

  data:{
    infos: [{
      name: 'Vue',
      age: 19,
      imageUrl: 's3.aws.amazon.com'
    }, {
      name: 'Vue 2',
      age: 20,
      imageUrl: 's3.aws.amazon.com2'
    }],
    msg: 'Hello Vuejs!'
  },

  methods:{
    getData: function(){
      axios.get('http://localhost:3000/getData')
        .then(function(result){
          this.infos = result.data
          console.log(infos)
        })
        .catch(function(err){
          console.log(err)
        })
    }
  }
})
<div id="app">
  {{msg}}
  <button v-on:click="getData">Get Data</button><br><br>
  <div v-for="info in infos">
    <br>
    <span>Name: {{info.name}}</span><br>
    <span>Age: {{info.age}}</span><br>
    <span>Image: {{info.imageUrl}}</span><br>
  </div>
</div>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="index.js"></script>

Here is the image of what I am getting.

The default values get rendered and also at the right the array gets logged.

The complete code is here https://github.com/siddiquiehtesham/fullstack-vue-nodejs-api


回答1:

In your axios request, this is not bound to your Vue instance.

Use arrow function instead to keep the right context:

getData: function() {
  axios.get('http://localhost:3000/getData')
  .then(result => {
    this.infos = result.data
    console.log(this.infos)
  })
  .catch(err => {
    console.log(err)
  })
}

or set a self variable before the request:

getData: function() {
  let self = this
  axios.get('http://localhost:3000/getData')
  .then(function(result) {
    self.infos = result.data
    console.log(self.infos)
  })
  .catch(function(err) {
    console.log(err)
  })
}
  • 发表于 2019-03-18 09:25
  • 阅读 ( 212 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除