Nativescript-Vue 超时后关闭模态

Nativescript-Vue close modal after timeout

我正在从 Nativescript-Vue 函数打开模态组件,该函数可以正常打开

this.$showModal(SuccessModal).then(() => { console.log('Modal Closed') });

我可以从模式中的按钮调用 $modal.close,但如果我尝试从 mounted() 挂钩调用它,则会得到 $modal is undefined

我希望模式在三秒超时后自行关闭,而不是用户必须在模式外部单击。

我该怎么做?

当使用传统的函数语法时,您会丢失当前上下文 (this),请使用箭头函数来避免这种情况。

setTimeout(() => {
    this.$modal.close();
}, 3000);

或者您必须在变量中保留对上下文的引用

var me = this;
setTimeout(function() {
    me.$modal.close();
}, 3000);

这是对@Manoj 回复的转折。 如果您愿意,可以在本机(非箭头)函数中使用 .bind(),而不是使用外部变量来绑定全局 this,如下所示:

setTimeout(function() {
    this.$modal.close();
}.bind($this), 3000);