Doing a Get using Axios (Vue.js)
I'm trying to pull a list of names coming from a json ( http://pokeapi.co/api/v2/pokemon ) using the axios but I do not understand why I get the error
TypeError: Cannot set property 'pokemons' of undefined
Being my console.log is returning the list correctly, follows the Code of my Vue component:
<template>
<div class="w-cards">
<div v-for="pokemon in pokemons" class="card">
<h1>{{pokemon.name}}</h1>
</div>
</div>
<script>
import axios from 'axios'
export default {
data() {
return {
pokemons: {
},
}
},
created: function() {
this.buscaPokemons();
},
methods: {
buscaPokemons: function(){
axios.get('http://pokeapi.co/api/v2/pokemon')
.then(function(res){
console.log(res);
console.log(res.data.results);
this.pokemons = res.data.results;
})
.catch(function(err){
console.log(err);
})
}
},
}
</script>
3
Author: bfavaretto, 2017-08-09
1 answers
The problem is that this
in the context of this callback function is no longer your Vue instance. You can use a arrow function :
.then( res => {
console.log(res);
console.log(res.data.results);
this.pokemons = res.data.results;
});
Or save a reference to the Vue instance before:
buscaPokemons: function(){
var vm = this;
axios.get('http://pokeapi.co/api/v2/pokemon')
.then(function(res){
console.log(res);
console.log(res.data.results);
vm.pokemons = res.data.results;
})
.catch(function(err){
console.log(err);
})
}
4
Author: bfavaretto, 2017-08-09 01:58:31