首页 文章

TypeError:无法设置未定义的属性'posts' - Vuejs

提问于
浏览
2

我用VueJs和Laravel创建了SPA . 主页我通过api laravel得到所有帖子,axio响应有数据对象 . 但我无法更新帖子属性 .

  • chrome调试工具出错:

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

我在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);
    });
  },
}

2 回答

  • 5

    您正在使用常规函数作为回调,这意味着 this 引用更改 . 你需要在这里使用箭头功能 . () => {} .

    axios.get('/api/posts')
        .then((response) => {
          this.posts = response.data;
        })
        .catch((error) => {
          console.log(error);
        });
    
  • 1

    首先,您在props属性中定义了 posts . 你不应该改变子组件的道具 . 道具是One-Way-Data-Flow

    您可以在数据属性中初始化 posts ,如下所示:

    data(){
        return{
            posts: null
        }
    }
    

    然后,您可以通过API获取数据并将其分配给data属性中的 posts

    this 在你 then 函数中没有指向vue实例 . 所以你做得更好

    created () {
         var vm = this;
        axios.get('/api/posts')
        .then(function (response) {
          vm.posts = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
      },
    }
    

    或者你是=>这样的功能

    created () {
        axios.get('/api/posts')
        .then( (response) => {
          this.posts = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
      },
    }
    

相关问题