【发布时间】:2020-07-09 14:00:54
【问题描述】:
我正在构建一个拦截器来处理我的Nuxt 应用程序中来自@nuxtjs/axios 的错误,但是当我尝试从axios 插件调用vue-sweetalert2 以显示它抛出的错误消息时:$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 实例?
感谢您的帮助。
【问题讨论】:
标签: vue.js vuejs2 axios nuxt.js vue-sweetalert2