I'm building an interceptor to handle errors from @nuxtjs/axios in my Nuxt app, but when I try to call vue-sweetalert2 from the axios plugin to show the error messages it throws me: $swal is not a function.
I have an alerts plugin and imported it to plugins section in nuxt.config, I use it to import Sweetalert globally and to handle a global loader, it works in other moments, but not when trying to call it from axios:
//plugins/alerts.js
import Vue from 'vue'
// I remove the following two lines when I import swal directly as a module in nuxt.config.js
import VueSweetalert2 from 'vue-sweetalert2';
Vue.use(VueSweetalert2);
Vue.mixin({
methods: {
alertLoading(action, message = "") {
if (action === "show") {
this.$swal.fire({
title: message,
imageUrl: "/img/Loader.gif",
allowOutsideClick: false,
showConfirmButton: false,
showCancelButton: false
});
} else {
this.$swal.close()
}
},
alertError(title, msg = undefined) {
this.$swal(title, msg, 'error')
}
}
})
My axios.js plugin:
/* I've trid importing it directly and doesn't work
import Vue from 'vue'
import VueSweetalert2 from 'vue-sweetalert2';
Vue.use(VueSweetalert2);*/
export default async ({ app, $axios }, inject) => {
$axios.defaults.withCredentials = true;
$axios.defaults.mode = "no-cors"
$axios.onError(error => {
cont response = error.response
if (response && response.data && response.data.msg) {
this.$swal("Error", response.data.msg, "error") // TypeError: Cannot read property '$swal' of undefined
// app.$swal("Error", response.data.msg, "error") //app.$swal is not a function
}
})
}
I've tried adding this code also to my plugin with no success:
const swal = require('vue-sweetalert2')
swal({
title: 'Error',
text: 'Error',
confirmButtonColor: "#895CF2",
confirmButtonText: 'Close',
type: 'error'
})
How do I call $swal from this axios instance? Is there a way to access Nuxt's this instance?
Thanks for your help.
This error appears when the
vue-sweetalert2is not properly configured as a Nuxt module. Your Nuxt config should contain the following entry in themodulesarray:nuxt.config.js:
Also, you don't need to explicitly install the plugin:
plugins/axios.js:
GitHub demo