当前位置:首页 > 移动开发 > 正文

Vue ElementUI Axios报错: Uncaught (in promise) TypeError: Cann

2024-03-31 移动开发

从头再来!!!

出错的代码如下:

        login() {
                this.loading = true
                let userInfo = {account: this.loginForm.account, password: this.loginForm.password, captcha: this.loginForm.chptcha}
                this.$api.login.login(userInfo).then( function(res) {
                    if (res.msg != null) {
                        this.$message({message: res.msg, type: ‘error‘})
                    } else {
                        Cookies.set(‘token‘, res.data.token)
                        sessionStorage.setItem(‘user‘, userInfo.account)
                        this.$router.push(‘/‘)
                    }
                    this.loading = false
                }).catch(function(res) {
                    this.$message({message: res.msg, type: ‘error‘})
                })
            },

 

今天遇到这个问题,网上有两大解决思路,

一种是保存好this。

https://www.jianshu.com/p/344df9332bbc

**在调用axios之前先保存this,const that = this,然后在回调中使用that代替this;

第二种,感觉高档点,使用ES6的=>箭头函数。

https://www.cnblogs.com/xifengxiaoma/p/9535700.html

        login() {
                this.loading = true
                let userInfo = {account: this.loginForm.account, password: this.loginForm.password, captcha: this.loginForm.chptcha}
                this.$api.login.login(userInfo).then( (res) => {
                    if (res.msg != null) {
                        this.$message({message: res.msg, type: ‘error‘})
                    } else {
                        Cookies.set(‘token‘, res.data.token)
                        sessionStorage.setItem(‘user‘, userInfo.account)
                        this.$router.push(‘/‘)
                    }
                    this.loading = false
                }).catch(function(res) {
                    this.$message({message: res.msg, type: ‘error‘})
                })
            },

使用箭头函数替代普通函数,ES6中的箭头函数 “=>” 内部的 this 属于词法作用域,由上下文确定(也就是由外层调用者vue来确定)。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/yidong/11153.html