【问题标题】:Laravel vue axios explanation needed需要laravel vue axios解释
【发布时间】:2018-08-11 12:58:24
【问题描述】:

我正在尝试理解Vue,它的依赖项(新手)只需要帮助来理解 axios 的工作方式,这样我就可以清楚了。

如果我使用下面的代码,它可以返回我的数据:

methods: {
            load: function() {
                axios.get('/api/projects')
                .then(
                    response => {
                        this.projects =  (response.data.projects);
                    }     
                )
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }

但如果我使用下面的代码,它不会返回数据:

methods: {
            load: function() {
                axios.get('/api/projects')
                .then(function (response) {
                    this.projects =  (response.data.projects);
                })
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }

区别仅在于.then 部分。

【问题讨论】:

  • 检查您的网络浏览器的调试控制台,我认为您遇到了 CORS 问题developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  • 不要调试任何东西,一切都按预期工作。只需谷歌搜索“箭头功能”并在 MDN 上阅读箭头和普通功能之间的区别。并关注thiscontext
  • @jesugmz 谢谢......
  • @VladislavLadicy 谢谢......

标签: laravel vue.js axios


【解决方案1】:

this 指的是两个函数中的不同对象。 写console.log(this),你会看到箭头函数中的那个是指Vue实例。然而,另一个是指另一个对象。可能window。对于function() {},您无法通过this 访问Vue 实例。您需要事先将其存储在变量中。

var vm = this;
axios.get('/api/projects')
            .then(function (response) {
                console.log(this); // undefined or other object
                console.log(vm); // vue instance
                vm.projects =  (response.data.projects);
            })

更多详情请查看另一个SO post

【讨论】:

    【解决方案2】:

    来自MDN

    箭头函数没有自己的this;使用封闭执行上下文的 this 值。

    需要解释的不是axios。这就是 this 关键字在不同上下文中的行为方式。你的第一个方法使用了一个叫做箭头函数的东西,它自己没有这个,所以它使用当前上下文的this。但是你的第二种方法确实有它自己的这个。

    因此,为了让第二种方法起作用,您必须在闭包之外缓存 this,如下所示:

    methods: {
                load: function() {
                    var that = this;
                    axios.get('/api/projects')
                    .then(function (response) {
                        that.projects =  (response.data.projects);
                    })
                    .catch(function (error) {
                        this.errors.push(error);
                        console.log(error);
                    })
                }
            }
    

    然后它就会起作用。

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2019-01-01
      相关资源
      最近更新 更多