【问题标题】:vue2 & promise How to Update Variable?vue2 & promise 如何更新变量?
【发布时间】:2019-03-18 21:47:41
【问题描述】:

我在构造函数中有一个带有变量的类,我尝试发出 ajax 请求并更新变量。但是该变量不在我的范围内。我该怎么办?

import Axios from "axios";

class ajaxTest{
    constructor() {
        this.resultOfAjax=" Mein Test";
    }

    set(id){
        return new Promise(function(resolve, reject) {
            Axios.get('/api/v1/ajax/'+id)  
            .then(function (response) {
                this.resultOfAjax=response.data;
                resolve(200);
                console.log("Test");
            });
        })
    }
}
export default ajaxTest;

我还尝试更新我的 loadingCircle 变量,但它不起作用。我认为这是同样的错误。是这样吗?

const app = new Vue({
    el: '#app',
    data: {
      loadingCircle: true,
      ajaxTest: new ajaxTest()
    },
    methods: {
      handleClick: function(id) {
        console.log("Das ist ein Test die ID ist:"+id); 
        this.ajaxTest.set(id).then( function(status){
          console.log("Status "+status);
          this.loadingCircle=false;
        });
      }
    },
    components: {
      examplecomponent
    }
});

【问题讨论】:

    标签: ajax vuejs2


    【解决方案1】:

    如果你使用function,那么里面的this和外面的this是不一样的。解决方案是改用粗箭头表示法。

    const app = new Vue({
        el: '#app',
        data: {
          loadingCircle: true,
          ajaxTest: new ajaxTest()
        },
        methods: {
          handleClick: (id) => {
            console.log("Das ist ein Test die ID ist:"+id); 
            this.ajaxTest.set(id).then( (status) => {
              console.log("Status "+status);
              this.loadingCircle=false;
            });
          }
        },
        components: {
          examplecomponent
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2017-05-19
      • 2021-07-30
      • 2020-11-10
      相关资源
      最近更新 更多