nuxt.jsvuejs3sweetalert2nuxt3.js

Add sweet alert 2 to nuxt3 project


I'm struggling to integrate sweet alert 2 as a plugin into a nuxt3 app. I'm trying to use vue-sweetalert2 but I at some point it define global variables.

// Inside the install function
vue.prototype.$swal = swalFunction;
vue['swal'] = swalFunction;

Could you please help me, how to access these global variable? The documentation do not show that.

I guess the goal would be to have inside my plugin something like:

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

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(VueSweetalert2)

  return {
    provide: {
      swal: swalFunction // <- how to access this ?
    }
  }
})

Solution

  • I'm learning nuxt3 too.Here is how I use sweet alert 2 in my app of nuxt3.

    plugins/swal.js

    import Swal from "sweetalert2";
    import "@sweetalert2/theme-bootstrap-4";
    const $swal = {
        install: (Vue, options) => {
            Vue.config.globalProperties.$swal = Swal.mixin(options);
        },
    }
    export default defineNuxtPlugin((nuxtApp) => {
        nuxtApp.vueApp.use($swal, {
            reverseButtons: true,
            confirmButtonText: "confirmText",
            cancelButtonText: "cancelText",
            confirmButtonColor: "#84bd00",
        });
    });
    

    Usage in components

    <script>
        export default {
          const fn = getCurrentInstance().appContext.config.globalProperties;
          fn.$swal.fire({
              title: "hello",
              timer: 2000,
          });
        }
    </script>
    

    Or use by provide and inject, My plugins/swal.js will be like this.

    import Swal from "sweetalert2";
    import "@sweetalert2/theme-bootstrap-4";
    const options = {
        reverseButtons: true,
        confirmButtonText: "confirmText",
        cancelButtonText: "cancelText",
        confirmButtonColor: "#84bd00",
    }
    const $swal = {
        install: (Vue, options) => {
            Vue.provide("$swal", Swal.mixin(options));
        },
    }
    export default defineNuxtPlugin((nuxtApp) => {
        nuxtApp.vueApp.use($swal, options);
    });
    

    Usage in components

    <script>
        export default {
          const swal = inject("$swal");
          swal.fire({
              title: "hello",
              timer: 2000,
          });
        }
    </script>
    

    Hope it's helpful.