首页 > 解决方案 > 如何使用 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.js

解决方案


你应该运行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。


推荐阅读