简体   繁体   中英

Structuring the axios callback in Vue

Question

What am I missing or doing wrong in my code if I just want to display a joke in my project?

WIP demo on codepen


Sample JSON response

在此处输入图片说明

HTML

new Vue({
  el: '#app',
  data:{
    jokes: []
  },
  created(){
    this.GetJokes();  
  },
  methods: {
     GetJokes () {
      axios.get('https://08ad1pao69.execute-api.us-east-1.amazonaws.com/dev/random_joke')
      .then(response => {

          let joke = response.data[0];

          let apiInfo = {
            setup: joke.setup,
            line: joke.punchline
          };
          this.jokes.push(apiInfo)
      })
    }
  }
})

JS - babel

 new Vue({ el: '#app', data:{ jokes: [] }, created(){ this.GetJokes(); }, methods: { GetJokes () { axios.get('https://08ad1pao69.execute-api.us-east-1.amazonaws.com/dev/random_joke') .then(response => { let joke = response.data[0]; let apiInfo = { setup: joke.setup, line: joke.punchline }; this.jokes.push(apiInfo) }) } } }) 

Your response is not an array. You just need

let joke = response.data

And that will fix your code.

Here is your pen updated .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM