client/src/components/utilities/Notifications.vue

57 lines
1.5 KiB
Vue

<template>
<div class="notifications">
<Modal v-for="notification in notifications.getNotifications" :key="notification.id" :isModalOpen="true" @modal:close="closeNotification(notification.id)">
<template #modalHeader v-if="notification.title">
<h3 class="modal-title">{{ notification.title }}</h3>
</template>
<template #modalBody v-if="notification.message">
<p>{{ notification.message }}</p>
</template>
</Modal>
</div>
</template>
<script setup lang="ts">
import { useNotificationStore } from '@/stores/notifications'
import { useSocketStore } from '@/stores/socket'
import Modal from '@/components/utilities/Modal.vue'
import { onMounted, onUnmounted, ref, watch } from 'vue'
const notifications = useNotificationStore()
const socket = useSocketStore()
function closeNotification(id: string) {
notifications.removeNotification(id)
}
function setupNotificationListener(connection: any) {
connection.on('notification', (data: { message: string }) => {
notifications.addNotification({
message: data.message
})
})
}
onMounted(() => {
const connection = socket.getConnection
if (connection) {
setupNotificationListener(connection)
} else {
// Watch for changes in the socket connection
watch(
() => socket.getConnection,
(newConnection) => {
if (newConnection) setupNotificationListener(newConnection)
}
)
}
})
onUnmounted(() => {
const connection = socket.getConnection
if (connection) {
connection.off('notification')
}
})
</script>