【问题标题】:Updating a vuejs alert component from a fetch return value从获取返回值更新 vuejs 警报组件
【发布时间】:2019-12-25 20:13:23
【问题描述】:

我在更新 vuetify v-alert 中的文本时遇到了困难。

我有一个登录系统并返回 sessionid 的函数 我遇到的问题是,在下面的代码sessionID.then() 中,vue 组件属性未定义或无法更新。

Vue.component('query-status', {
  template: `
    <div>
      <v-alert :type="type">
        {{ alertText }}
      </v-alert>
    </div>`,
  data() {
    return {
      alertText: '',
      type: 'success'
    }
  },
  methods: {
    checkQueryStatus: function() {
      var sessionID = login();
      sessionID.then(function(result) {
        this.alertText = result;
      });
    }
  }
});

我不明白我在这里做错了什么,为什么sessionID.then 块不能访问alertText 属性?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuetify.js


    【解决方案1】:

    您没有绑定this 指针,内部函数将无法访问它。

    您可以通过使用局部变量来解决此问题:

    checkQueryStatus : function() {              
      var sessionID = login();
      var that = this;
      sessionID.then(function(result) {
        that.alertText = result;
      });
    }
    

    或者使用 es6 arrow function:

    checkQueryStatus : function() {              
      var sessionID = login();  
      sessionID.then(result => {
        this.alertText = result;
      });
    }
    

    或将this 指针与Function.prototype.bind 绑定:

    checkQueryStatus : function() {              
      var sessionID = login();  
      sessionID.then(function(result) {
        this.alertText = result;
      }.bind(this));
    }
    

    您也可以为此使用async / await

    methods: {
      async checkQueryStatus() {              
        this.alertText = await login();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2017-09-17
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多