[Vuejs]-How to use Sweetalert in main.js Vue 3

0👍

Explanation

I faced the same problem when using Vue 3, and I wanted to use sweetalert2 in my router/index.js to add an alert when a user goes to an unauthorized route.

The same problem will appear if you want to use a sweetalert2 in store/index.js after calling an action fetching data from the backend.

To work around this problem, you must use the native package of sweetalert2, then you can use swal in any .js file.

By the way, I don’t want to install any external package, so I found that when you are installing the vue-sweetalert2, the native package will be installed also (because it is a dependency of vue-sweetalert2).

Workaround

All you have to do is:

  • Keep what you had done in main.js (to use sweetalert2 inside components).
  • In any .js file where you want to use swal, add this import Swal from 'sweetalert2/dist/sweetalert2', and now you can access and use Swal.fire({}).

Example

I will attach an example of what I want to do (in my case), and how I work around the problem:

My main.js file:

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
import router from './router';
import VueSweetalert2 from 'vue-sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';

const app = createApp(App);

app.use(store);
app.use(router);
app.use(VueSweetalert2);

app.mount('#app');

My router/index.js

import { createRouter, createWebHistory } from 'vue-router';
import Swal from 'sweetalert2/dist/sweetalert2';
import store from '../store/index';

const router = createRouter({
  routes: [
    // ...
  ],
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta['requiresAuth']) && store.state.auth.isAuthenticated === false) {
    Swal.fire({
      toast: true,
      position: 'bottom-end',
      showConfirmButton: false,
      timer: 3000,
      timerProgressBar: true,

      icon: 'error',
      title: 'Permission denied',
      text: 'You are not authenticated to access this page.'
    });

    next({
      name: 'login',
      params: { nextUrl: to.fullPath }
    });
  }

  next();
});

export default router;

-1👍

i think you need to try withoud condition first,
try only sweet alert without :

axios.interceptors.response.use(function (response) {
    return response
}, function (error) {
    console.log(error.response.data.message)
    if (error.response.data.message === 'Unauthenticated.') {
        swal({
            title: "Session Expired",
            text: "Your session has expired. Would you like to be redirected to the login page?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes",
            closeOnConfirm: false
        }).then((result) => {
            if (result.value) {
                window.location.href = "/login"
            }
        });     
}
    return Promise.reject(error)
})

u can try

https://www.npmjs.com/package/vue-sweetalert2

Leave a comment