首页 > 解决方案 > 1秒后自动隐藏VueJS中的元素

问题描述

好的,所以我是 Vue 的新手(基本上是 JS 的新手,但我现在正在玩 Vue),我想做的是在模板标签内自动隐藏一个元素(不是点击)的一个组件。在 jQuery 中,这看起来像:

$(function() {
    setTimeout(function() {
        $(".hideElement").hide()
    }, 1000);
});

但是这在 Vue 中是如何工作的?我的组件如下所示:

<template>
<div>
 <h1 class="hideElement"> HELLO </h1>
</div>
</template>

<script> // nothing here 
</script>

<style> // nothing here
</style>

我知道如何在单击按钮时切换元素,但我只想在每次用户输入此组件(这是一个新的“页面”)时在 1 秒后自动隐藏它而没有任何单击事件

标签: vue.jsvuejs2settimeoutvue-cli

解决方案


您可以在数据对象中添加一个属性并使用 v-show 指令来确定元素是否应该可见。如果布尔值为假,则元素被隐藏,如果为真,则元素可见。

创建实例后同步调用的方法 Created。

<template>
    <div>
        <h1 v-show="elementVisible" class="hideElement"> HELLO </h1>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                elementVisible: true
            }
        },

        created() {
            setTimeout(() => this.elementVisible = false, 1000)
        }
    }
</script>

推荐阅读