在Nuxt中使用axios插件中的vue-sweetalert2

时间:2020-07-09 14:00:54

标签: vue.js vuejs2 axios nuxt.js vue-sweetalert2

我正在构建拦截器来处理我的@nuxtjs/axios应用中的Nuxt的错误,但是当我尝试从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实例?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果vue-sweetalert2未正确配置为Nuxt模块,则会出现此错误。您的Nuxt配置应在modules数组中包含以下条目:

nuxt.config.js:

module.exports = {
  modules: [
    'vue-sweetalert2/nuxt',
  ]
}

此外,您无需显式安装插件:

plugins / axios.js:

// XXX: No need to install `vue-sweetalert2` here
// import Vue from 'vue'
// import VueSweetalert2 from 'vue-sweetalert2';
// Vue.use(VueSweetalert2);

export default async ({ app }) => {
  app.$swal('hello world')
}

GitHub demo