vue.js - 如何使用 Vue.js 在响应函数中运行方法
问题描述
当我从 API 获得成功响应时,我正在尝试运行一个方法,但该方法没有运行。我在这里做了一个简单的例子来展示。
test() 函数应该在我得到响应后执行,因为它调用了另一个 API 端点。这是 vue.js 代码。
var app = new Vue({
el: "#contents",
data: {
id: null,
details: [],
},
methods: {
fetchProductDetails: function(){
let vue = this;
axios.post("/api/get-details", {
id : id
})
.then(function (response) {
vue.details = response.data;
this.test();
})
.catch(function (error) {});
},
test: function () {
console.log(app.details);
}
},
mounted: function(){
this.fetchProductDetails();
},
});
解决方案
你应该运行vue.test()
而不是this.test()
,就像你使用vue.details = response.data
而不是this.details = response.data
。
在 中使用未命名函数时.then()
,this
不再指代您的 vue 应用程序,而是指未命名函数。您可以使用 ES6 箭头函数语法以避免必须设置this
为特定变量,因为箭头函数使用其父级的作用域this
而不是设置this
来引用自己:
axios.post("/api/get-details", { id: this.id })
.then(response => {
this.details = response.data;
this.test();
})
.catch(error => { console.log(error)});
然而,IE11 不支持箭头函数(以及一般的 ES6)。因此,如果您需要支持旧版浏览器,则需要使用 Babel 将其编译回 ES5 JavaScript。
推荐阅读
- python - 迭代列表并在迭代中创建具有字段名称的新列表
- c# - Azure 持久功能待处理,如何分类?
- variables - 打印 Ansible 变量
- typescript - Edge + Webdriver 17134 - 未加载扩展
- c# - 将 Rhinoscriptsyntax 从 Python 移植到 C#
- python - Python 3.7.1 的文件存在
- firebase - 使用 Cloud Functions 中的 Firebase 身份验证 signInAnonymously
- c++11 - 井字游戏二维数组填充字符
- java - 当您收到任何错误的响应代码时,如何在重定向后获取 URL?
- node.js - 使用node.js HapiJS和couchbase sdk异步返回空结果