我正在构建一个Vue CLI应用程序(Webpack模板),它使用Bootstrap显示模式窗口。我正在尝试从Vue组件的mounted()钩子中以编程方式显示该模型(请参见引导Vue 文档以编程方式调用该模型),如下所示:
<script>
export default {
name: 'ButtonComponent',
mounted() {
const showModal = sessionStorage.getItem('showModal');
if (showModal === 'yes') this.$refs.myModal.show();
}
}
</script>这个很好用。但是,如果我引入这样的setTimeout()函数,则无法使其工作:
<script>
export default {
name: 'ButtonComponent',
mounted() {
const showModal = sessionStorage.getItem('showModal');
if (showModal === 'yes') setTimeout(() => this.$refs.myModal.show(), 3500);
}
}
</script>为什么在3.5秒后不显示模态?超时工作,我知道这一点,因为我尝试了console.log()-ging从它得到一条消息。我认为这可能是因为Vue JS实例在计时器中不可用,所以我尝试声明一个const self = this;并调用setTimeout(() => self.$refs.myModal.show(), 3500);,但这也没有帮助。我在这里错过了什么?
发布于 2018-08-16 12:23:23
从句法上讲,是正确的。当您使用箭头函数时,这将从最初调用它的位置绑定到上下文。在您的例子中,这在setTimeout中表示Vue实例。尝试执行几个console.log调用,如:
setTimeout(() => {
console.log(this); // the vue instances
console.log(this.$refs); // the $refs
console.log(this.$refs.myModal); // the modal $ref
}, 3500)只是为了检查您的$ref是否存在。也许您的myModal组件还没有绑定?
https://stackoverflow.com/questions/51876118
复制相似问题