从获取返回值更新 vuejs 警报组件 [英] Updating a vuejs alert component from a fetch return value
问题描述
我无法更新 vuetify v-alert
.
I'm having difficulty in updating the text inside a vuetify v-alert
.
我有一个函数可以登录系统并返回一个 sessionid我遇到的问题是,在下面的代码 sessionID.then()
中,vue 组件属性未定义或无法更新.
I have a function that logs into a system and returns a sessionid
The issue I have is that within the below code sessionID.then()
the vue component properties are not defined or cannot be updated.
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
属性?
I don't understand what I am doing wrong here, why doesn't the sessionID.then
block have access to the alertText
property?
推荐答案
您没有绑定 this
指针,内部函数将无法访问它.
You didn't bind the this
pointer, the inner function will not have access to it.
您可以通过使用局部变量来解决此问题:
You can work around this by either using a local variable:
checkQueryStatus : function() {
var sessionID = login();
var that = this;
sessionID.then(function(result) {
that.alertText = result;
});
}
或者使用 es6 箭头函数:一个>
checkQueryStatus : function() {
var sessionID = login();
sessionID.then(result => {
this.alertText = result;
});
}
或将 this
指针与 Function.prototype.bind
:
or bind the this
pointer with Function.prototype.bind
:
checkQueryStatus : function() {
var sessionID = login();
sessionID.then(function(result) {
this.alertText = result;
}.bind(this));
}
作为替代,您也可以使用 async/await:
As an alternative you could also use async / await for this:
methods: {
async checkQueryStatus() {
this.alertText = await login();
}
}
这篇关于从获取返回值更新 vuejs 警报组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!