【问题标题】:Vue + axios returns undefinedVue + axios 返回未定义
【发布时间】:2018-04-18 09:00:48
【问题描述】:

我有 app.js 将 axios 和 VueAxios 导入为:

Vue.use(VueAxios, axios);

然后调用我的组件:

Vue.component('api-call', require('./components/PostComponent'));

在我的PostComponent我有一个简单的axios得到如下:

<script>
    export default {
        // name: "PostComponent"
        data() {
            return {
                post: {},
            }
        },
        methods: {
            getPosts: () => {
                console.log('started');
                //let that = this;
                let uri = 'https://jsonplaceholder.typicode.com/posts';
                this.axios.get(uri).then((response) => {
                        console.log(response);
                    })
            }
        },
        mounted(){
            this.getPosts()
        }
    }
</script>

因为我希望在组件加载开始时执行此操作,所以我使用的是mounted(为什么 Vue 没有构造函数让我感到困惑,甚至通过 isMounted 模式传递的反应。)

我做错了什么?

谢谢, 芽

【问题讨论】:

  • 错误信息是什么?

标签: laravel vue.js axios


【解决方案1】:

方法声明不能使用箭头函数。

https://vuejs.org/v2/api/#methods

请注意,您不应该使用箭头函数来定义方法 (例如加:()=> this.a++)。原因是箭头函数绑定了 父上下文,所以这不会是你期望的 Vue 实例,并且 this.a 将是未定义的。

这是正确定义方法的两种方式

  1.     getPosts: function() {
    
        }
    
  2. (如果你可以使用 ES6)

        getPosts() {
    
        }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2019-01-05
    • 2020-10-24
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多