gpt4 book ai didi

需要 Laravel vue axios 解释

转载 作者:搜寻专家 更新时间:2023-10-30 22:58:12 26 4
gpt4 key购买 nike

我正在尝试理解 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 部分。

最佳答案

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了解更多详情。

关于需要 Laravel vue axios 解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51799930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com