Search code examples
vue.jsvuejs3sweetalert2

calling SweetAlert2 inside Async method in VUE 3


I tried to pops out sweetalert if failed to retreive data from server

I've imported sweet alert in main.js :

import VueSweetalert2 from 'vue-sweetalert2'
import 'sweetalert2/dist/sweetalert2.min.css'

const app = createApp(App)
app.use(VueSweetalert2)
app.mount('#app')

And inside the Table.vue components i tried to call swal but got an error says (undefined $this.swal) instead :

<script>
import axios from 'axios'
import { onMounted, ref } from 'vue'

export default {
    setup() {
        let transactions = ref([])

        onMounted(() => {
            getTransactions()
        })

        async function getTransactions() {
            try {
                let { data } = await axios.get('http://127.0.0.1:8000/api/transactions')
                transactions.value = data.data
            } catch(e) {
                this.$swal('Something went wrong.')
            }
        }

        return {
            transactions
        } 

    }
}
</script>

Any suggestion how to solve this ?


Solution

  • You can't use this as the component instance inside setup() because the component has not been created yet. There are other ways to get that $swal property.

    vue-sweetalert2 exposes SweetAlert via app.config.globalProperties.$swal or as a provide-ed $swal prop.

    A simple way to use it in the Composition API is through inject():

    import { inject } from 'vue'
    
    export default {
        setup() {
            const swal = inject('$swal')
    
            async function getTransactions() {
                //...
                swal('Something went wrong.')
            }
        }
    }
    

    demo 1

    However, the vue-sweetalert2 docs recommend using sweetalert2 directly in this case:

    When using "Vue3: Composition API" it is better not to use this wrapper. It is more practical to call sweetalert2 directly.

    You can use sweetalert2 directly like this:

    import { onMounted, inject } from 'vue'
    import Swal from 'sweetalert2'
    
    export default {
      name: 'App',
      setup() {
        async function getTransactions() {
          //...
          Swal.fire('Something went wrong.')
        }
    
        onMounted(() => getTransactions())
      }
    }
    

    demo 2