vue.jsvuejs3quasar-framework

How to emit an Event in VueJS 3 outside of a component?


I have a component that has an action to delete items. At the end of this operation I'd like to inform the parent component to refresh its data.

<template>
  <div class="q-pa-md row items-start q-gutter-md">
    <div v-for="media in mediaItems" :key="media.uuid" >
      <MediaItemComponent :media="media" @delete="actionDelete" />
    </div>
  </div>
</template>

The script:

const actionDelete = (id: string) => {
  $q.dialog({
    dark: true,
    title: 'Confirm',
    message: 'Do you really want to delete the image?',
    cancel: true,
    persistent: true
  })
    .onOk(async () => {

      const success = await mediaStore.deleteMediaItem(id)
      if(success) {
        $q.notify({
          message: 'Image has been deleted successfully',
          color: 'positive',
          position: 'bottom'
        })

   // ----> Inform the parent component to refresh its list

        this.$emit('refreshList')
      }
    })
    .onCancel(() => {
      $q.notify({
        message: 'Action Cancelled',
        color: 'negative',
        position: 'bottom',
      })
    })
}

How can I achieve to inform the parent component that it shall refresh the list? I've read about using this.$emit but this is not defined here.


Solution

  • In Composition API:

    <script setup>
    
    const $emit = defineEmits(['refreshList']);
    
    //later in code
    
    $emit('refreshList');
    
    </script>