LoginSignup
14
15

More than 3 years have passed since last update.

【Vue.js】表示後、3秒経過したら自動的に消えるフラッシュメッセージのサンプルコード

Last updated at Posted at 2020-01-20

はじめに

表示後、3秒経過したら自動的に消えるフラッシュメッセージのサンプルコードを残します。

※単一ファイルコンポーネントにしていますので、コピペで挙動の確認が可能です。

環境

OS: macOS Catalina 10.15.1
Vue: 2.6.10

結論:コード

※コード内に簡単な説明を記載しています。

Sample.vue
<template>
  <div>

    <!-- v-ifで<script>内のshowがtrueであれば表示する -->
    <div
      class="flash"
      v-if="show === true"
    >
      this is flash message!
    </div>

    <!-- clickしたらmethods:{}内のshowFlashが発火する -->
    <button
      @click="showFlash"
    >
      show flash message
    </button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        show: false,
      }
    },

    // Vueインスタンスに変化があったら発動する
    updated() {

      // setTimeoutで3000ms後にshowをfalseにする
      setTimeout(() => {
        this.show = false}
        ,3000
      )
    },
    methods: {
      showFlash(){
        this.show = true;
      }
    }
  }
</script>

<style>
.flash {
  width: 200px;
  height: auto;
}
button {
  width: 200px;
  height: 30px;
  background: red;
  border-radius: 5px;
}
</style>

2020/01/22 追記 修正分

@aotoriii さんよりご教授頂き、リファクタリングしたものを以下に記載しております。

@aotoriii さん、わざわざご指摘ありがとうございます:bow_tone1:

Sample.vue
<template>
  <div>

    <!-- v-ifで<script>内のshowがtrueであれば表示する -->
    <div
      class="flash"
      v-if="show"
    >
      this is flash message!
    </div>

    <!-- 略 -->
</template>

<script>
  export default {
//...略
    methods: {
      showFlash(){
        this.show = true;
      // setTimeoutで3000ms後にshowをfalseにする
        setTimeout(() => {
          this.show = false}
          ,3000
        )
      }
    }
  }
</script>

おわりに

最後まで読んで頂きありがとうございました:bow_tone1:

どなたかの参考になれば幸いです:relaxed:

参考にさせて頂いたサイト(いつもありがとうございます)

14
15
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15