はじめに
表示後、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 さん、わざわざご指摘ありがとうございます
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>
おわりに
最後まで読んで頂きありがとうございました
どなたかの参考になれば幸いです