I'm trying to get data from an API in a Laravel Vue component. I get this error in the console:
TypeError: Cannot set property 'continents' of undefined
What am I missing?
This is my code:
<script>
export default {
mounted() {
console.log('Component mounted.');
},
created(){
this.loadData();
},
data() {
return {
continents: [],
}
},
methods: {
loadData: function() {
axios.get('/api/continents')
.then(function (response) {
// handle success
console.log(response.data);
this.continents = response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},
},
}
</script>
Here is the simple working demo of axios.get
request
var app = new Vue({
el: '#app',
data: {
users:[]
},
mounted(){
this.loadData();
},
methods:{
loadData:function(){
axios.get('https://jsonplaceholder.typicode.com/users').then(res=>{
if(res.status==200){
this.users=res.data;
}
}).catch(err=>{
console.log(err)
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<ol>
<li v-if="users.length>0" v-for="user in users">
{{ user.name }}
</li>
</ol>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With