javascript - 从获取返回值更新 vuejs 警报组件

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

我在更新 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 block 无法访问 alertText 属性?

最佳答案

您没有绑定(bind) 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 绑定(bind):

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

作为替代方案,您还可以使用 async / await为此:

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

关于javascript - 从获取返回值更新 vuejs 警报组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57576548/

相关文章:

javascript - 如何计算 JavaScript 数组的数量并获得这样的输出?

javascript - 如何在不循环的情况下向Javascript数组中的每个对象添加字段?

javascript - 如何在 JavaScript 中动态创建二维 (2D) 字符串数组

javascript - 我想在注册完成后在我的网站上运行一个新页面

javascript - 将 Google map 与 Vue.js 结合使用

google-maps - 谷歌地图 : Cannot read property 'setDirections' of undefined

javascript - 理解Vue中的 'this'关键字

vue.js - Router async beforeEach 触发两条路由

javascript - 我可以从一个 Vue.js 组件导出两个对象吗?

javascript - 如何在 Vue 中有条件地设置选定的选项