English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detaillierte Erklärung des this-Verweises bei der Verwendung von axios in vue

Einleitung

Wie bekannt ist, ist Axios ein Plugin für Vue-Resource nachfolgenden Vue-Datenanfragen-Plugins. Vue wurde auf2.0, der Autor Yu Da hat bekannt gegeben, dass er Vue-Resource aktualisiert, sondern empfiehlt Axios. Weitere detaillierte Informationen finden Sie hier: https://de.oldtoolbag.com/article/109444.htm

Dieser Artikel beschreibt das Problem mit der this-Bezeichnung bei der Verwendung von Axios in Vue. Viel Rede ist verfehlt, also schauen wir uns gemeinsam die detaillierte Erklärung an.

1.Lösung

Wenn Sie Axios für Netzwerkanfragen in Vue verwenden, werden Sie feststellen, dass this nicht auf Vue verweist, sondern auf undefined. Dies kann mit dem Pfeiloperator "=>" gelöst werden. Hier ist ein Beispiel:

methods: {
 loginAction(formName) {
 this.$axios.post('http://127.0.0.1/u/subLogin', {
  username: this.username,
  password: this.password
 });
  .then(function(response){
  console.log(this); //这里 this = undefined
  });
  .catch((error)=> {
  console.log(error); //箭头函数 "=>" 使 this 指向vue
  });
 });
 }
} 

2. 原因

ES6中的 箭头函数 "=>" 内部的 this 是词法作用域,由上下文确定(也就是由外层调用者vue来确定)。

3. 题外话

使用 "=>" 函数,就可以告别之前的两种写法了:

使用 bind(this) 来改变匿名函数的 this 指向

hack 写法 var _this= this; :

loginAction(formName) {
 var _this= this;
 this.$axios.post("...")
 .then(function(response){
  console.log(_this); //这里 _this 指向vue
 });
 });
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或工作具有一定的参考学习价值。如果有疑问,大家可以留言交流,谢谢大家对呐喊教程的支持。

声明:本文内容来自网络,版权归原作者所有。内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#oldtoolbag.com(在发邮件时,请将#更换为@进行举报,并提供相关证据。一经查实,本站将立即删除涉嫌侵权内容。)

Möchten Sie auch