javascript - 如何在 Vue 组件中调用 Promise 中的方法

标签 javascript vue.js vuejs2

<分区>

在 Vue 组件中:

import { someRequestMethod } from '@/api/requ'

...

methods: {
    testMethod() {
        someRequestMethod(someRequestData).then(function() {
            this.outMethod_01()
        }).then(function() {
            this.outMethod_02()
        })
    }

    outMethod_01() {
        console.log('I am an outer method 01.');
    }

    outMethod_02() {
        console.log('I am an outer method 02.');
    }
}

当我用 Promise 响应调用 testMethod 时。 然后我想在成功时调用 outMethod_01,在出错时调用 outMethod_02。 但我得到错误 outMethod_01 is undefinedoutMethod_02 is undefined

那么如何在Promise中调用外部方法呢?

最佳答案

您应该使用箭头函数语法 (params) => {...code} 而不是 function(params) {...code}。在箭头函数中,this 是从范围继承的。在常规函数中,this 是函数本身(它有自己的作用域)。

您可以在此处了解更多信息:https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

如果你不能使用 ES6 语法,你可以这样做:

methods: {
    testMethod() {
        var self = this;
        someRequestMethod(someRequestData).then(function() {
            self.outMethod_01()
        }).then(function() {
            self.outMethod_02()
        })
    }

    outMethod_01() {
        console.log('I am an outer method 01.');
    }

    outMethod_02() {
        console.log('I am an outer method 02.');
    }
}

关于javascript - 如何在 Vue 组件中调用 Promise 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54442983/

相关文章:

javascript - .js 文件中的 VueJS "new Vue()"不工作

javascript - 如何让对象在 v-bind 和 v-for 中使用

javascript - 如何使用 VueJS 或 JavaScript 在多维数组中进行搜索

javascript - 如何使用数组数组中的多个变量进行计算和显示(Vue+laravel)

javascript - 更改不确定的剑道进度条的颜色并为其添加自定义标签

c# - Odata 使用 Knockout Js 路由和访问它

vue.js - Vuetify 的 fab 按钮图标没有垂直居中

javascript - 如何使用过滤器在数组中的对象的多个键值中进行搜索?

javascript - 如何让用户禁用推送通知?

javascript - 无法读取未定义的属性 - javascript 类