1 秒后自动隐藏 VueJS 中的元素

Pol*_*sek 8 settimeout vue.js vuejs2 vue-cli

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

$(function() {
    setTimeout(function() {
        $(".hideElement").hide()
    }, 1000);
});
Run Code Online (Sandbox Code Playgroud)

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

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

<script> // nothing here 
</script>

<style> // nothing here
</style>
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*fek 16

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

方法 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>
Run Code Online (Sandbox Code Playgroud)