首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Nuxt中axios插件中的vue-甜警报2

使用Nuxt中axios插件中的vue-甜警报2
EN

Stack Overflow用户
提问于 2020-07-09 14:00:54
回答 1查看 4.4K关注 0票数 0

我正在构建一个拦截器,以在我的Nuxt应用程序中处理来自Nuxt的错误,但是当我试图从axios插件调用vue-sweetalert2以显示错误消息时,它抛出了我的$swal is not a function

我有一个警报插件并将其导入到nuxt.config中的plugins部分,我使用它从全局导入Sweet警报并处理全局加载程序,它在其他时刻工作,但在试图从axios调用它时不起作用:

代码语言:javascript
运行
复制
//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插件:

代码语言:javascript
运行
复制
/* 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
        }
    })
}

我也尝试将这段代码添加到插件中,但没有成功:

代码语言:javascript
运行
复制
const swal = require('vue-sweetalert2')
swal({
    title: 'Error', 
    text: 'Error', 
    confirmButtonColor: "#895CF2",
    confirmButtonText: 'Close',
    type: 'error'
})

如何从这个axios实例调用$swal?有办法访问Nuxt的this实例吗?

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2020-07-13 06:48:56

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

nuxt.config.js:

代码语言:javascript
运行
复制
module.exports = {
  modules: [
    'vue-sweetalert2/nuxt',
  ]
}

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

plugins/axos.js:

代码语言:javascript
运行
复制
// 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演示

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62816611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档