I have this vue.js component that uses axios to retrive a json array of joke
objects :
<template>
<div id="show-jokes-all">
<h2>Showing all jokes</h2>
<div v-for="joke in jokes">
<h2>{{joke.title}}</h2>
<article>{{joke.body}}</article>
<hr>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'showJokes',
data () {
return {
jokes:[]
}
},
methods: {
},
created() {
axios.get('http://127.0.0.1:8090/api/jokes).then(function(data){
//console.log(data); works fine
this.jokes = data.body;
});
}
}
</script>
When I log the result in console it's fine but when I try to put it in jokes
array I get
Uncaught (in promise) TypeError: Cannot set property 'jokes' of undefined
This may be a trivial error but as a newbie to vue.js I'm stock on this so appreciate your hints.
.then(data => this.jokes = data.body)
instead of the function you have. Or use a closure or bind as described in the above link. – Bertthis.$http
) instead ofaxios
.this
is treated differently inside the callbacks of those two libraries. – Bert.then(data => this.jokes = data.body)
above, but it should have been.then(response => this.jokes = response.data)
. – Bert