我刚制作了一个flash消息组件,它从eventBus接收flash消息,然后在消失之前显示flash消息3秒钟。该组件如下:
<template>
<transition name="fade">
<div v-if="visible" v-bind:class="type" role="alert">{{ message }}</div>
</transition>
</template>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s
}
.fade-enter, .fade-leave-to {
opacity: 0
}
</style>
<script>
import EventBus from '../../config/EventBus';
export default {
name: 'flash-view',
data() {
return {
type: '',
message: '',
visible: false,
};
},
mounted() {
EventBus.subscribeFlashMessage(data => this.setData(data));
setTimeout(() => (
this.visible = false
), 3000);
},
methods: {
setData(data) {
this.setType(data.type);
this.message = data.message;
this.visible = true;
},
setType(type) {
this.type = `alert alert-${type}`;
},
},
};
</script>
该组件适用于第一个闪存消息,但是如果随后触发闪存消息或者如果我更改路由(VueRouter),则闪存消息不会消失。我认为这是因为javascript被重新触发,这会使setTimeout的效果无效,但是我不知道如何在Vue中解决这个问题。
答案 0 :(得分:0)
由于Belmin Bedak的帮助,我已设法解决了这个问题。现在使用created()而不是mounted()实现以下内容,因为每次更新周期都会重新触发已安装。 Created()设置一次监听器,watch用于检查可见是否已更改(当新事件被推送到监听器时会发生这种情况)。如果更改了visible,则会正确触发setTimeout。
<template>
<transition name="fade">
<div
v-if="visible"
v-bind:class="type"
role="alert"
v-text="message"
>
</div>
</transition>
</template>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s
}
.fade-enter, .fade-leave-to {
opacity: 0
}
</style>
<script>
export default {
name: 'flash-view',
data() {
return {
type: '',
message: '',
visible: false,
};
},
created() {
this.$on('flashMessage', data => this.setData(data));
},
methods: {
setData(data) {
this.type = `alert alert-${data.type}`;
this.message = data.message;
this.visible = true;
},
setFadeOut() {
setTimeout(() => (
this.visible = false
), 2500);
},
},
watch: {
visible: 'setFadeOut',
},
};
</script>