我正在构建一个拦截器来处理@nuxtjs/axios
我的Nuxt
应用程序中的错误,但是当我尝试vue-sweetalert2
从 axios 插件调用以显示错误消息时,它会抛出我:$swal is not a function
.
我有一个警报插件并将其导入到插件部分nuxt.config
,我使用它全局导入 Sweetalert 并处理全局加载器,它在其他时刻有效,但在尝试从 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')
}
}
})
我的axios.js
插件:
/* 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
}
})
}
我也尝试将此代码添加到我的插件中,但没有成功:
const swal = require('vue-sweetalert2')
swal({
title: 'Error',
text: 'Error',
confirmButtonColor: "#895CF2",
confirmButtonText: 'Close',
type: 'error'
})
如何从此 axios 实例调用 $swal?有没有办法访问 Nuxt 的this
实例?
谢谢你的帮助。