Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot set property 'posts' of undefined - Vuejs

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.

  • Error in chrome debug tool:

TypeError: Cannot set property 'posts' of undefined - Vuejs

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);
    });
  },
}
like image 714
Nguyen Manh Linh Avatar asked Oct 16 '25 14:10

Nguyen Manh Linh


1 Answers

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);
    });
like image 146
Suraj Rao Avatar answered Oct 18 '25 08:10

Suraj Rao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!