Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在回调函数中访问“正确”的 this #80

Closed
Dream4ever opened this issue Sep 11, 2019 · 0 comments
Closed

在回调函数中访问“正确”的 this #80

Dream4ever opened this issue Sep 11, 2019 · 0 comments
Labels
JS Javascript

Comments

@Dream4ever
Copy link
Owner

Dream4ever commented Sep 11, 2019

需求描述

Vue 的 methods 中调用了 axios 来向后端发送/请求数据,如何在 axios 的回调中访问 Vue 实例的数据(data)?

方案调研

用关键词 how to vue instance inside axios callback 进行 Google,第一个链接就是 Stack Overflow 上的提问,质量应该很高。
提问的网址:javascript - Accessing VUE JS's data from Axios - Stack Overflow
点进去看,第一个最高票回答给出了在 axios 回调中访问 Vue 实例数据的三种方法:

方案一

创建对 Vue 实例的引用,比如 var self = this,然后在回调中访问。

知识点:以前经常见到 var self = this 的写法,一直不明白有什么用,这次遇到作用域的问题了,终于有点理解了。

方案二

回调函数写成箭头函数,就能直接在回调中访问 Vue 实例了。

知识点:又想起来在一些地方要求不能用箭头函数,也是跟作用域有关,看来需要注意箭头函数的作用域问题。

相关链接:Arrow functions - JavaScript | MDN

方案三

将 axios 用 bind 方法绑定到 Vue 实例上,axios.get().then().bind(this)。

知识点:以前读犀牛书看到 bind 方法,没有多深的体会,现在知道还可以这样用,涨姿势了。

相关链接:Function.prototype.bind() - JavaScript | MDN

拓展阅读

@Dream4ever Dream4ever added the JS Javascript label Sep 11, 2019
@Dream4ever Dream4ever changed the title 在回调函数中访问正确的 this 在回调函数中访问“正确”的 this Sep 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JS Javascript
Projects
None yet
Development

No branches or pull requests

1 participant