Vue使用axios----ReferenceError: axios is not defined问题解决

问题1:ReferenceError: axios is not defined

在这里插入图片描述
问题代码:

const requrl = '/user/find/1'
axios.get(requrl).then(response => {
    const user = response.data
    this.username = user.username
    this.age = user.age
}).catch(
    function (error) {
        // 请求失败处理
        alert('请求失败!')
    })

解决方案1
main.js加上Vue.prototype.$axios = axios
axios.get改为this.$axios.get调用,修改后不再报错

import axios from 'axios'
//其他vue组件中就可以this.$axios调用使用
Vue.prototype.$axios = axios
const requrl = '/user/find/1'
this.$axios.get(requrl).then(response => {
    const user = response.data
    this.username = user.username
    this.age = user.age
}).catch(
    function (error) {
        // 请求失败处理
        alert('请求失败!')
    })

解决方案2:结合vue-axios插件,安装插件后,就不需要将axios绑定到Vue原型链上了,组件内通过this.axios调用
npm install axios vue-axios --save

import axios from 'axios'
import VueAxios from "vue-axios";
Vue.use(VueAxios,axios)
//其他vue组件中就可以this.$axios调用使用
//Vue.prototype.$axios = axios
const requrl = '/user/find/1'
this.axios.get(requrl).then(response => {
    const user = response.data
    this.username = user.username
    this.age = user.age
}).catch(
    function (error) {
        // 请求失败处理
        alert('请求失败!')
    })
问题2,并发测试时,TypeError: Cannot read property ‘$axios’ of undefined

在这里插入图片描述
报错代码如下:

function getUserget() {
    return this.$axios.get('/user/find/1')
}
function getUserpost() {
    return this.$axios.post('/user/find',{id:2})
}
this.$axios.all([getUserget(), getUserpost()])
    .then(this.$axios.spread(function (res1, res2) {
        // 两个请求现在都执行完成
        const user1 = res1.data
        const user2 = res2.data
        console.log(user1.username)
        console.log(user2.username)
    }));

原因未知,有知道的大佬还望不吝赐教
无奈只得在app.vue(我是在这里做的测试)中再次引入
import axios from 'axios'
再次引入,直接用axios就行

function getUserget() {
    return axios.get('/user/find/1');
}
function getUserpost() {
    return axios.post('/user/find',{id:2});
}
  • 36
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值