Reputation: 729
I create SPA with VueJs and Laravel. Homepage i get all posts via api laravel and axio responsive had data object. But i can not update to posts property.
My code in Wellcome.vue
import { mapGetters } from 'vuex'
import axios from 'axios'
export default {
name: 'welcome',
layout: 'default',
metaInfo: { titleTemplate: 'Welcome | %s' },
computed: mapGetters({
authenticated: 'authCheck'
}),
data: () => ({
title: 'Demo Blog',
}),
props: {
posts: {
type: Object
}
},
created () {
axios.get('/api/posts')
.then(function (response) {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
Upvotes: 4
Views: 4875
Reputation: 31352
First of all you defined posts
in your props property. You should not mutate a prop from child component. Props are One-Way-Data-Flow
you can inititialize posts
in you data property as follows:
data(){
return{
posts: null
}
}
Then you can fetch data via your API and assign it to your posts
in the data property
this
in you then
function does not point to the vue instance.
So its better you do it like this
created () {
var vm = this;
axios.get('/api/posts')
.then(function (response) {
vm.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
Or you an => function like this
created () {
axios.get('/api/posts')
.then( (response) => {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
Upvotes: 1
Reputation: 29625
You are using a regular function as a callback which means this
reference changes. You need to use arrow function here . () => {}
.
axios.get('/api/posts')
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
});
Upvotes: 9