【问题标题】:Use vue-sweetalert2 from axios plugin in Nuxt在 Nuxt 中使用来自 axios 插件的 vue-sweetalert2
【发布时间】: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


    【解决方案1】:

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

    nuxt.config.js:

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

    另外,您不需要显式安装插件:

    插件/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

    【讨论】:

    • 请提供代码链接以重现问题
    • 我认为我的问题与 SSR 有关,我打印 app.$swal 并给我未定义,但其他插件如 app.$auth 工作。
    猜你喜欢
    • 2020-04-02
    • 2020-06-29
    • 2021-01-24
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2019-09-06
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多