use nuxt plugin instead of function

This commit is contained in:
Jeffrey Hsu 2024-12-18 08:42:00 +08:00
parent be50b1cc5f
commit 7efa425c85
8 changed files with 40 additions and 18 deletions

View File

@ -1,7 +1,8 @@
<script setup lang="ts">
const loading = ref<HTMLDivElement | null>(null)
const {$mitt} = useNuxtApp()
emitter.on('startLoading', on => {
$mitt.on('startLoading', on => {
if (on) {
loading.value?.classList.remove('stop')
removeMobileTopColor()

View File

@ -1,6 +1,6 @@
<script lang="ts" setup>
const {$mitt} = useNuxtApp()
const notifications = ref<INotification[]>([]);
const typeClasses = {
success: 'bg-green-100 text-green-800 border border-green-400',
error: 'bg-red-100 text-red-800 border border-red-400',
@ -19,10 +19,10 @@ const addNotification = (notification: INotification) => {
};
emitter.on('eventBus', addNotification)
$mitt.on('eventBus', addNotification)
onBeforeUnmount(() => {
emitter.off('eventBus', addNotification);
$mitt.off('eventBus', addNotification);
});
</script>

View File

@ -1,10 +0,0 @@
import mitt from 'mitt'
type Events = {
openPost: IPost
startLoading: boolean
eventBus: INotification
}
const emitter = mitt<Events>()
export default emitter

View File

@ -1,10 +1,13 @@
<script setup lang="ts">
import type { NuxtError } from '#app'
import { setMobileTopColor } from '~/composables/function'
const props = defineProps({
error: Object as () => NuxtError
})
const {$mitt} = useNuxtApp()
const errorMessages: Record<string, { icon: string; title: string; message: string }> = {
'400': {
icon: '❓',
@ -42,7 +45,12 @@ const errorContent = computed(() => errorMessages[props.error!.statusCode] || er
console.error(props.error)
onMounted(() => {
emitter.emit("startLoading", false)
$mitt.emit("startLoading", false)
setMobileTopColor()
})
onUnmounted(() => {
removeMobileTopColor()
})
</script>

View File

@ -1,7 +1,8 @@
<script setup lang="ts">
const {$mitt} = useNuxtApp()
onMounted( () => {
emitter.emit('startLoading', false)
$mitt.emit('startLoading', false)
})
</script>

View File

@ -1,6 +1,8 @@
<script setup lang="ts">
const {$mitt} = useNuxtApp()
onMounted(() => {
emitter.emit("startLoading", false)
$mitt.emit("startLoading", false)
})
</script>

View File

@ -1,6 +1,7 @@
<script lang="ts" setup>
import {computed, onMounted, ref} from "vue";
const {$mitt} = useNuxtApp()
const recentPosts = ref<IPost[] | null>(null);
const recentActivities = ref<IActivity[] | null>(null);
const isLoading = ref({
@ -76,7 +77,7 @@ await reloadPosts()
await reloadActivities()
onMounted(() => {
emitter.emit('startLoading', false)
$mitt.emit('startLoading', false)
})
</script>

19
plugins/mitt.ts Normal file
View File

@ -0,0 +1,19 @@
import mitt from 'mitt'
type Events = {
openPost: IPost
startLoading: boolean
eventBus: INotification
}
export default defineNuxtPlugin(() => {
const emitter = mitt<Events>()
return {
provide: {
mitt: emitter
}
}
})